DateTime startDate = DateTime.ParseExact(txtstart.Text, "MM/dd/yyyy", null);
DateTime endDate = DateTime.ParseExact(txtend.Text, "MM/dd/yyyy", null);
string n1 = DropDownList2.SelectedItem.Text;
if (DropDownList1.SelectedItem.Text == "Membership")// here you can add selectedindex as well
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ProjectConnectionString"].ToString());
con.Open();
SqlDataAdapter adapter = new SqlDataAdapter("select * from Membership_det where updateDate between #Start and #End and FID ="+n1+"", con);
adapter.SelectCommand.Parameters.Add("#Start", SqlDbType.Date).Value = startDate;
adapter.SelectCommand.Parameters.Add("#End", SqlDbType.Date).Value = endDate;
}
……..
……..
Above is a part of a code to display the data in the grid view.I am displaying * from Membership_det and also need to display faculty name from other table…how to add the query with the above query..displaying * from membership _det table and faculty name from other table
FID MembNo MembType Validity Remarks UpdateDate
100 23 basn 6 dgag 9/5/2013 12:00:00 AM
200 566 basn 6 adhu 9/6/2013 12:00:00 AM
In this table i need to add Faculty name..it should be fetched from other table..
You can JOIN tables as below. Change the Relationship and the column names based on your tables. it is better if you can use parameter for FID as well
SELECT m.*, f.Name
FROM Membership_det m
INNER JOIN faculty f
ON m.FID = f.FID
WHERE m.updateDate between #Start and #End and m.FID =#FID ;
You can join Memberhip_det table with the other table to retrieve faculty_name. But these two tables should have a common connecting field or primary and foreign keys.
Also try using stored procedures rather than inline queries
Try to use union for your two sql select statements
UNION
The UNION command is used to select related information from two tables, much like the JOIN command. However, when using the UNION command all selected columns need to be of the same data type. With UNION, only distinct values are selected.
Make foreign key relation ship to FID column on faculty table and change your query as follows
select Membership_det.MembNo, Membership_det.MembType,Membership_det.Validity,Membership_det.Remarks,Membership_det.UpdateDate,faculty.facultyname FROM Membership_det INNER JOIN faculty ON Membership_det.FID = faculty.FID
WHERE Membership_det.updateDate between #Start and #End and Membership_det.FID =#FID ;
Related
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).
I need to do a full outer join on 2 datatables dinamically, I don't know what columns are in the datatables but they will be the same in each table, I also only have the name of the column I need to do the join on in a variable. Is there a way of doing this?
What I need to do is join 2 datatables in a C# script. I'm using a Dataflow in an SSIS to get data from a couple of files, and at the end I need to compare the 2 final sets of data. I need to to this on whatever 2 datatables as long as they have the same columns, so I can't finish the process in an SSIS as I need to specify the columns.
The GetData() I just use it in case I need to compare 2 tables but donnesPROD and donnesDEV are filled from object variables in the SSIS.
Here's my code so far :
DataTable donnesPROD = GetData(connectionPROD, sql_request);
DataTable donnesDEV = GetData(connectionDEV, sql_request);
Here's the code for GetData :
DataTable GetData(string cs, string query)
{
OleDbConnection conn = new OleDbConnection(cs);
conn.Open();
OleDbCommand cmd = new OleDbCommand(query, conn);
DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader());
conn.Close();
return dt;
}
I have the list of the columns in another datatable, and I have the name of the primary key in a string variable key. From here I need to be able to do a fullouterjoin of donnesPROD and donnesDEV on key. Can this be done this way? Or is there a way of generating the script code it self dynamically and then execute it?
You have two options.
Conditional joins
If you don't know the specific column name, but you do have some idea what the column name might be, you could do a conditional join like this:
CREATE PROCEDURE ExampleDynamicJoin(#JoinColumn AS VarChar(40))
AS
BEGIN
SELECT *
FROM TableA
JOIN TableB ON (#JoinColumn = 'ColumnA' AND TableA.ColumnA = TableB.ColumnA)
OR (#JoinColumn = 'ColumnB' AND TableA.ColumnB = TableB.ColumnB)
OR (#JoinColumn = 'ColumnC' AND TableA.ColumnC = TableB.ColumnC)
END
You may not get the best performance out of this (the conditional joins will confuse the query engine and it may not pick the best index, if it picks one at all). If the table is very large you could also do something like this. It is a bit painful-looking but will get better performance:
CREATE PROCEDURE ExampleDynamicJoin(#JoinColumn AS VarChar(40))
AS
BEGIN
IF (#JoinColumn = 'ColumnA') BEGIN
SELECT *
FROM TableA
JOIN TableB ON TableA.ColumnA = TableB.ColumnA
END
IF (#JoinColumn = 'ColumnB') BEGIN
SELECT *
FROM TableA
JOIN TableB ON TableA.ColumnB = TableB.ColumnB
END
IF (#JoinColumn = 'ColumnC') BEGIN
SELECT *
FROM TableA
JOIN TableB ON TableA.ColumnC = TableB.ColumnC
END
END
If TableA or TableA are part of a larger query, and you'd end up duplicating tons of SQL, you could always extract the resultset for just TableA and TableB into a temporary table, then use the temporary table in the larger query.
Dynamic SQL
If you don't have the foggiest about the column name and there are tons of possibilities, you could construct the SQL as a string and join that way. You should validate the column name that is passed in; not only will that make sure the column actually exists, but it will prevent the dynamic SQL from being constructed when #JoinColumn contains an injection attack, since legal column names do not contain SQL statements. Example:
CREATE PROCEDURE ExampleDynamicJoin(#JoinColumn AS VarChar(40))
AS
BEGIN
DECLARE #Sql AS VarChar(MAX)
IF NOT EXISTS
(
SELECT 0
FROM syscolumns c
JOIN sysobjects o ON o.id = c.id
WHERE o.Name = 'TableA'
AND c.Name = #JoinColumn
)
RAISERROR (15600,-1,-1, 'ExampleDynamicJoin'); //Throw error if column doesn't exist
SET #Sql =
'SELECT *
FROM TableA
JOIN TableB ON TableA.' + #JoinColumn + ' = TableB.' + #JoinColumn
sp_ExecuteSql #Sql
END
Or, if you don't use stored procedures,
DataTable ExampleDynamicJoin(string joinColumn)
{
if (!ValidateColumn(joinColumn)) throw new ArgumentException();
var sql = String.Format(
#"SELECT *
FROM TableA
JOIN TableB ON TableA.{0} = TableB.{0}",
joinColumn
);
using (var connection = GetConnectionFromSomewhere())
{
using (var cmd = new SqlCommand
{
CommandText = sql,
CommandType = CommandType.Text,
Connection = connection
})
{
var reader = cmd.ExecuteReader();
var table = new DataTable();
table.Load(reader);
return table;
}
}
}
When using dynamic SQL you should always use parameters if possible. But you can't use parameters as a column name, so in this case you have to concatenate. When concatenating, ALWAYS white list the inputs. That is why I included a function named ValidateColumn which could look like this:
bool ValidateColumn(string columnName)
{
switch columnName.ToUpper()
{
case "COLUMNA":
case "COLUMNB":
case "COLUMNC":
return true;
default:
return false;
}
}
My table name is tblEvent and its columns are EventID, Name, Description, EventTypeID, TotalBudget, CustomerID, EventStatus, EventDate
I want to select the latest 3 records.
I have tried this:
public DataTable HomeEvents()
{
string query = "select TOP 3 tblEvent.*, tblCustomer.Name as 'CustomerName', tblCustomer.Photo AS 'CustomerPhoto' from tblEvent ORDER BY EventID DESC, tblCustomer where tblEvent.CustomerID = tblCustomer.CustomerID";
List<SqlParameter> lstParams = new List<SqlParameter>();
DataTable dt = DBUtility.SelectData(query, lstParams);
return dt;
}
The order by clause should be after the where clause:
select top 3
tblEvent.*,
tblCustomer.Name as 'CustomerName',
tblCustomer.Photo AS 'CustomerPhoto'
from
tblEvent
where
tblEvent.CustomerID = tblCustomer.CustomerID
order by
EventID desc,
tblCustomer
Note: If EventID is auto-incremented (primary key, identity) and the records are actually created in the order that they occured, then the field would be in increasing order over time. Otherwise you would need to use the EventDate field for sorting (as Tareq Alothman suggested).
As Guffa said, Order By comes after where, and you need to
"Order By EventDate DESC"
Change your SQL statement to read
... ORDER DESC BY ...
This will sort in reverse order, the first three are now the last three.
I have an table name dbo.EmpInfo having 4 columns
1-UserId 2-SubUserId 3-Year 4-Status
I have an another table (in other database) name dbo.EmpInfo1 having 4 columns
1-UserId 2-SubUserId 3-Year 4-Status
UserId may be repeating in both tables..
Now i have to find those UserId from Both tables whose Status="Success" and this status count is < 10 and bind these values in Gridview..
for ex-I have an UserId say mayank#gmail.com and in dbo.EmpInfo it has status count=5(Status="Success") and in dbo.EmpInfo1 it has status count=7 so from both tables the total count for mayank#gmail.com is 12 so we have to bind this userId in Gridview. and Gridview having all the above columns..
i have a procedure -
ALTER proc [dbo].[sp_countUserDetails]
as
begin try
begin transaction
Select distinct(UserId) from EmpInfo where Status='Success'
union all
Select distinct(UserId) from MyDB.dbo.EmpInfo1 where Status='Sucess'
commit transaction
end try
in my .cs file i used
SqlDataReader dr = ms.sp_SelectExecuter("sp_countUserDetails");
DataTable dt = new DataTable();
dt.Load(dr);
foreach (DataRow DR in dt.Rows)
{
ms = new MethodStore();
ms.sp_SelectExecuter("sp_usercount", "#userid", (DR["UserId"]).ToString());
}
and the Procedure is-
ALTER Procedure [dbo].[sp_usercount]
#userid varchar(50)
as
declare #count1213 dec =0, #count1314 dec =0;
begin try
begin transaction
select #count1314= count(UserId) from EmpInfo where Status='Status' and UserID=#userid;
select #count1213= count(UserId) from MyDB.dbo.EmpInfo1 where Status='Success' and UserID=#userid;
select #count1213+#count1314 as 'Count'
if((#count1213+#count1314)>=10)
insert into MyTaxCafe.dbo.demo values (#userid);
commit transaction
end try
bt the table dbo.demo doesn't contain distinct UserId..because our Procedure
[dbo].[sp_countUserDetails]
give Distinct values from both table but at due to Union there is an redundancy can we control it because Same UserId may be Exist in both tables
First you need a SQL to query two database , you may try it like this
SELECT Status FROM [database1].[dbo].[TableName] AS t1 INNER JOIN [database2].[dbo].[TableName] AS t2
ON (t1.UserId = t2.UserId)
WHERE Status='Success'
GROUP BY Status
Having COUNT(Status) < 10
in your C# code , use SqlDataAdapter to fill DataTable,
then set DataGridView's field DataSource = DataTable
You must use union from your query to get expected result.
Your columns are same in both tables so u can use union without any changes
for example
select * (select * from TableName1
where Status = 'Success'
union
select * from TableName2
where Status = 'Success'
) A
where count(Status)<10
group by SubUserId, Year, Status
try this.
I am selecting two records between two dates, when doing this i am experiencing repeated record, I have used the word distinct but its not working: This is how my query looks:
public List<i> searchTwoDates(string firstDate, string secondDate)
{
DateTime fdate = Convert.ToDateTime(firstDate);
string realfirstDate = fdate.ToLongDateString();
DateTime sdate = Convert.ToDateTime(secondDate);
string realsecondDate = sdate.ToLongDateString();
List<i> date = new List<i>();
SqlConnection conn = new SqlConnection(....);
SqlCommand command = new SqlCommand(#"SELECT distinct * From TableName WHERE Cast(columnName AS DATE) > #columnName AND CAST(columnName AS DATE) < #columnName1 ORDER BY columnName1 Desc", conn);
command.Parameters.AddWithValue("#columnName", realfirstDate);
command.Parameters.AddWithValue("#columnName2", realsecondDate);
conn.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Mod d = new Mod();
here i get my column names....
date.Add(d);
}
conn.Close();
return date;
}
I also have a unique ID in my database so we can use that to retrieve unique record but how would i write that?
Currently i am getting repeated records
ID FName sName Date
1 John JAck 2013-9-07
2 Linda Bush 2013-10-07
3 Linda Bush 2013-11-07
This is what i want
ID FName sName
1 John JAck 2013-9-07
2 Linda Bush 2013-11-07
This is the records between 2013-9-07 to 2013-11-07. in between these records i dont want any repeated ID
[migrated from comments]
You should use select distinct id, fname, sname from table. If you don't need the date, then this will work, no repetitions.
Try this
Select Max(ID),FName,sName,Max(Date)
FROM Table1
Where Date > 'SomeDate' And Date < 'SomeDate'
Group By FName,sName
Don't try using BETWEEN
SELECT DISTINCT ID,FName,sName,Date
FROM Table1
WHERE Date BETWEEN 'Date1' And 'Date2'
UPDATE
Because of the two different dates and IDs in the question above you should use grouping. This gives you:
SELECT MIN(ID),FName,sName, MIN(Date)
FROM Table1
WHERE Date BETWEEN 'Date1' And 'Date2'
ORDER BY ID
GROUP BY FName,sName
DISTINCT will not work as there are different IDs and dates for each record.
The above query will give you the first occuring ID. You can change the ORDER BY to Date to get the earliest. Or you want the most recent then use MAX instead of MIN and use ORDER BY with DESC.