Select some of rows in C# database connection - c#

I used database connection for connect to database and I selected some of rows in database table, like this code:
OleDbConnection objConnection = new OleDbConnection("server=localhost;database=sample;Data Source=|DataDirectory|\\sample.accdb");
objDataAdapter = new OleDbDataAdapter("SELECT description, category, account, price FROM SampleTable WHERE Select_ID = 12", objConnection);
now this code select 16 rows from SampleTable where Select_ID is 12 after that i need rows 3,5,7 how can i select this rows?

DataTable dt = new DataTable(); // get your data into this datatable
DataRow[] dr;
dr = dt.Select("WHERE Select_ID = 12");
if (dr.Length > 0)
{
//do something
}

You can use the ROW_NUMBER function. If you use it in the query you have, you will select by ROW_NUMBER of ALL rows. If I read correctly, you want rows 3,5,7 of the result set, so you would have to use a subquery:
SELECT * FROM (
SELECT description, category, account, price FROM SampleTable WHERE Select_ID = 12
) WHERE ROW_NUMBER() IN (3,5,7)
In the inner query, you are getting the 16-row result. The outer query now uses that result as a table/data source and selects the rows you need.

if order by column "id", then
SELECT t.description, t.category, t.account, t.price FROM (
SELECT ROW_NUMBER() OVER (ORDER BY id) as RowN, description, category, account, price FROM SampleTable WHERE Select_ID = 12
) as t WHERE RowN in (3,5,7)
else (ORDER BY id) change to your column

If your DataTable already contains those 16 rows but you want only row 3,5,7:
int[] indexes = { 2, 4, 6 };
dataTable1 = dataTable1.AsEnumerable()
.Where((row, index) => indexes.Contains(index))
.CopyToDataTable();
If you use a database that supports ranking functions you could use ROW_NUMBER. If you use SQL-Server >=2005 this works:
string sql = #"
WITH CTE AS
(
SELECT description, category, account, price,
rn = ROW_NUMBER() OVER (ORDER BY Select_ID, description, category, account, price)
FROM SampleTable
WHERE Select_ID = 12
)
SELECT description, category, account, price
FROM CTE
WHERE rn IN ( 3, 5, 7 );"

Related

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.

How to bind Gridview when performing union on two database and applying some conditions on it?

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.

How do I select distinct values between two dates

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.

Need to calculate number of rows in sql on the basis of modify date

What I'm trying to do is to calculate the number of rows of the table which updated 2 days means suppose I have some data like this:
ID Name Department DateTime ModifyDate
---------------------------------------------------------------------------
1 XXXXX IT 2013-09-10 09:53:01.000 2013-09-10 09:55:01.000
2 YYYYY Tech 2013-09-09 10:00:00.000 2013-09-10 12:00:00.000
3 WWWW IT 2013-09-09 08:09:00.000 2013-09-10 09:09:00.000
Now there are two rows which modify on 10 sep
I want a query which will give me the count of no. of row modify per day.
My desired out will be like this
No. of column
2
try this
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand("Select count(ID) from TableName where ModifyDate>=#Today and ModifyDate<#NextDay", connection))
{
command.Parameters.Add(new SqlParameter("Today", DateTime.Today ));
command.Parameters.Add(new SqlParameter("Nextday", DateTime.Today.AddDays(1) ));
int count = 0;
int.TryParse( command.ExecuteScalar().ToString() , out count);
}
}
select Distinct Count(ID) from Table where ModifyDate between '2013-09-10' and '2013-09-11'
SELECT COUNT(ID) FROM TableX WHERE ModifyDate BETWEEN #FromDate and #ToDate;
Pass your start and end dates to the appropriate variables
You might want to use something like
SELECT count(ID)
FROM TableName
GROUP BY CAST(ModifyDate AS DATE)
SELECT CONVERT(DATE,ModifiedDate) AS DATE, count(ID) AS TotalUpdated
FROM TableName
GROUP BY CONVERT(DATE,ModifiedDate)
Try this query.
select count(*) as [No. of column] from Table1
where CAST(ModifyDate as Date) = 'Sep 10, 2013'
Replace 'Sep 10, 2013' with GetDate() if you want to filter on the current date.

Merging 2 datatables in to 1 datatable with same number of rows.

How can i merge two Datatables into the same row. I am using different stored procedures to get data into datasets. In asp.net using c#, i want to merge them so there are same number of rows as table 1 with an added column from table 2.
For example:
DataTable table1 = dsnew.Tables[0];
DataTable table2 = dsSpotsLeft.Tables[0];
table1.Merge(table2);
This is fetching me 4 rows instead of 2 rows. What am i missing here? Thanks in advance!!
You cannot use the method Merge in this case, instead you should create new DataTable dt3, and then add columns and rows based on the table 1 and 2:
var dt3 = new DataTable();
var columns = dt1.Columns.Cast<DataColumn>()
.Concat(dt2.Columns.Cast<DataColumn>());
foreach (var column in columns)
{
dt3.Columns.Add(column.ColumnName, column.DataType);
}
//TODO Check if dt2 has more rows than dt1...
for (int i = 0; i < dt1.Rows.Count; i++)
{
var row = dt3.NewRow();
row.ItemArray = dt1.Rows[i].ItemArray
.Concat(dt2.Rows[i].ItemArray).ToArray();
dt3.Rows.Add(row);
}
Without knowing more about the design of these tables, some of this is speculation.
What it sounds like you want to perform is a JOIN. For example, if you have one table that looks like:
StateId, StateName
and another table that looks like
EmployeeId, EmployeeName, StateId
and you want to end up with a result set that looks like
EmployeeId, EmployeeName, StateId, StateName
You would perform the following query:
SELECT Employee.EmployeeId, Employee.EmployeeName, Employee.StateId, State.StateName
FROM Employee
INNER JOIN State ON Employee.StateId = State.StateId
This gives you a resultset but doesn't update any data. Again, speculating on your dataset, I'm assuming that your version of the Employee table might look like the resultset:
EmployeeId, EmployeeName, StateId, StateName
but with StateName in need of being populated. In this case, you could write the query:
UPDATE Employee
SET Employee.StateName = State.StateName
FROM Employee
INNER JOIN State ON Employee.StateId = State.StateId
Tested in SQL Server.
Assuming you have table Category and Product related by CategoryID, then try this
var joined = from p in prod.AsEnumerable()
join c in categ.AsEnumerable()
on p["categid"] equals c["categid"]
select new
{
ProductName = p["prodname"],
Category = c["name"]
};
var myjoined = joined.ToList();
Sources
LINQ query on a DataTable
Inner join of DataTables in C#
http://social.msdn.microsoft.com/Forums/en-US/adodotnetdataset/thread/ecb6a83d-b9b0-4e64-8107-1ca8757fe58c/
That was a LINQ solution. You can also loop through the first datatable and add columns from the second datatable

Categories

Resources