How can I join SQL Server tables in C#? - c#

I have a column named LEADER in 16 tables in my SQL Server database. I'd like to join all the tables to show the Leader column and the table it belongs to in my database
SqlCommand cmd = new SqlCommand("Select GroupLeaders.ID, Account.Leader, Engineers.Leader from GroupLeaders inner join Account on GroupLeaders.id = Account.Leader", conn);

You can try this
SELECT 'Table1' AS Source, LEADER FROM Table1
UNION ALL
SELECT 'Table2' AS Source, LEADER FROM Table2
UNION ALL
SELECT 'Table3' AS Source, LEADER FROM Table3
UNION ALL
...
SELECT 'Table16' AS Source, LEADER FROM Table16
Note: Make sure to replace "Table1", "Table2", etc. with the actual names of your tables. Also, the LEADER column should be present in all 16 tables for this query to work.

Related

Retrieve data from different tables

I want to retrieve data from two tables like below. I have a Products table which has P_id, P_name columns and a BATCH table with p_id_fk as a foreign key to the Products table.
This is my query; I want to retrieved from product's name from the Product table because I have stored the Products table primary key as a foreign in the Batch table.
SqlDataAdapter sda = new SqlDataAdapter("Select batch_id, quantity, left_qty, purchaseDate, manufacturing_date, expiryDate from batch where Convert(DATE, expiryDate, 103) BETWEEN #from AND #to", con);
sda.SelectCommand.Parameters.AddWithValue("#from", Convert.ToDateTime(datePicker1.SelectedDate.Value).ToString("yyyyMMdd"));
sda.SelectCommand.Parameters.AddWithValue("#to", Convert.ToDateTime(datePicker2.SelectedDate.Value).ToString("yyyyMMdd"));
If you want to retrieve data from two tables you need to use a SQL JOIN
I am not sure of the exact make up of your tables but something like the below
Select batch_id,
product_name,
quantity,
left_qty,
purchaseDate,
manufacturing_date,
expiryDate
from batch B
INNER JOIN Products P
ON P.P_id = B.P_id
where Convert(DATE,expiryDate,103) BETWEEN #from AND #to
you need to have a join or cross apply here.
Option 1 - inner join:
Select
b.batch_id,pd.product_name,quantity,left_qty,
purchaseDate,manufacturing_date,expiryDate from batch b
inner join product pd on pd.p_id = b.p_id where Convert(DATE,expiryDate,103)
BETWEEN #from AND #to
Option 2 cross apply:
Select
b.batch_id,pd.product_name,quantity,left_qty,
purchaseDate,manufacturing_date,expiryDate from batch b
cross apply
(
select product_name from product p
where p.p_id = b.p_id
) pd
where Convert(DATE,expiryDate,103)
BETWEEN #from AND #to
for more about cross apply look here.
Not sure if I understood your question correctly, but I believe for your query you are looking for something simple as JOIN between Products and Batch tables:
SELECT
P.P_id,
P.P_name,
B.batch_id,
B.product_name,
B.quantity,
B.left_qty,
B.purchaseDate,
B.manufacturing_date,
B.expiryDate
FROM Batch AS B
INNER JOIN Products AS P
ON B.p_id_fk = P.P_id
WHERE CONVERT(DATE, B.expiryDate, 103) BETWEEN #from AND #to
p_id_fk name you provided might be not an actual column name in Batch table but rather the name of the foreign key constraint itself as it appears by the naming convention (_fk suffix).

Select distinct duplicated rows from 1:n tables in SQL Server

I am trying to select customers and their orders in one query, but I get customer and his orders in datatable which customer table columns repeated for each order.
I tried DISTINCT, GROUP BY but can't do it.
SQL:
select *
from Customer, Order
where Order.CustomerID = Customer.CustomerID
and Customer.CustomerID = '2'
Tables:
Since there cannot be different columns for each row you can't do it without having duplicates. Consider reading data separately, once for the customer and once for her orders.
i want to get all customers and orders the query count will grow.if i
have 3 customer i want to get orders and customers in one query.not 6
times query execution.
You do not need to perfrom a separate query for each customer. You just need a single query for all customers and a single query for all orders. Then you may connect them in application layer rather than a single query.
But if you argue that you have too many customers and too many orders to hold them all in memory, well, then you may perform a separate query for each customer. That's a tradeoff between memory and CPU.
This is a very rare query, but this my understanding of your need :p.
select *
from (
select 'CustomerID' as col1, 'CustomerName' as col2, 'ContactName' as col3,
'Address' as col4, 'City' as col5, 'PostalCode' as col6, 'Country' as col7, 0 as ord
union all
select CustomerID, CustomerName, ContactName, Address, City, PostalCode, Country, 1 as ord
from Customers
union all
select 'OrderId', 'CustomerID', 'EmployeeID', 'OrderDate', 'ShipperID', Null, Null, 0 as ord
union all
select OrderId, CustomerID, EmployeeID, OrderDate, ShipperID, Null, Null, 2 as ord
from Orders) res
In the result with ord = 0 you have titles, with ord = 1 you will have customers only and with ord = 2 you will have orders, and you can use this query with this condition:
where (col1 = #customerId and ord = 1) or (col2 = #customerId and ord = 2)
You can add or ord =0 if you want to add titles in your output.

Querying with Datatable a combination of multiple select in one row

I'll proceed to explain by showing you a simple example
table NAMES
ID_NAMES
NAME
table AGES
ID_AGES
AGE
this is my query
SELECT
(
select NAME
from NAMES
where ID_NAME=1
) as thisismyname,
(
select AGE
from AGES
where ID_AGE=50
) as thisiymyage
I'm expecting results like
thisismyname, thisismyage
I'm perfectly aware that it's completely stupid, because I could do a join and get an easy query, but there is NO links between tables and this will be a result of a combination of 50 select, not just two.
It's working, but I want a DataTable where I can query with just using
mydatatable[0]["thisismyname"]
Actually it's giving me results only with an ExecuteScalar, and SQLDataReader gives me empty DataTable
using (var conn = Connection)
{
DbCommand mycommand = GetCommand(conn, sql);
DbDataReader reader = mycommand.ExecuteReader();
dt.Load(reader);
reader.Close();
conn.Close();
}
This should be done in SQL. If you have a problem then you can try to do distinct. You don't need indexes on your tables to join them.
select distinct n.NAME, a.AGE
from NAMES n
JOIN AGES a on a.ID = n.ID
where n.ID=1
You could create some custom code where you get two data tables and merge them somehow, but I don't think that it would be a good solution.
If for some reason the ID's on AGES and NAMES are different and cannot be joined, then you should probably create a SQL query with 2 parameters AgeId and NameId:
select distinct n.NAME, a.AGE
from NAMES n
cross join AGES a
where n.ID=#nameId
and a.ID=#ageId

SQL query help in where clause

string sql1 = "select jname, jcode
from heardt,judge,main
where heardt.jud1 = judge.jcode and main.fil_no=heardt.fil_no and ..
main.fil_no= ";
I have a form in which user enters a reg_no on entering reg_no only name and address is displayed, in the same table there is fil_no which i want to be used in my above query to link to another table.
how can i specify it in my above query,in the third AND condition? please guide me.
You are talking about JOINing tables I believe? Joins are very simple and are written as thus :-
SELECT t1.column1,t1,column2,t2.column1,t2.column2
FROM table1 t1
JOIN table2 t2
ON t1.key1 = t2.key1
WHERE .....
You can join as many tables as you require and have multiple JOIN types.
See more here :-
http://msdn.microsoft.com/en-us/library/ms191472.aspx

Trackablecollection problem in EF

I newbie in EF.
I have Table A linked together to table B, by passing a primary ID from table A which is a secondary ID on table B Iam trying to retrieve an object from table B.
But I am getting trackableCollection'1[Object name(from table B)]
Any suggestions?
I am trying to retrieve using stored proc
here is the code:
select * from tableB as da
left outer join tableA as cr on da.ID = cr.ID
where da.ID = #d

Categories

Resources