PDA

View Full Version : Cho hỏi về record count



snoopy
11-11-2003, 10:19
Cho minh hoi đối tựơng SQLDataReader, Dataset hay SqlDataAdapter có hàm nào để lấy số record trả về khi thực hiện xong câu query select k day? Thanks

khangle
11-11-2003, 13:02
Mình không biết là trong .NET có hàm nào trả lại số record khi thực hiện câu lệnh query không nhưng bạn có thể dùng aggregation function "COUNT" trong SQL để đếm số record trả lại.

VD: SELECT COUNT (*) FROM MY_TABLE
sẽ cho ta số record trong bảng MY_TABLE

:)

danceswithwolves
11-11-2003, 14:44
dataTable.Rows.Count trả về record count.

snoopy
11-11-2003, 16:53
Ví dụ mình muốn thực hiện query select * from Country Order by Name để lấy dữ liệu từ các field như: Name, CountryID...

Vậy nếu dùng câu select count(*) from Country thì nó chỉ trả vể số record thôi, chứ đâu có dữ liệu? Có thể kết hợp count(*) với các filed khác để lấy ra dữ liệu nếu record > 0 k?

KEM_WALL
12-11-2003, 19:53
bạn có thể ghép mà
select count(*), * from Country........
hoặc select bình thường, sau đó như anh Sói nói, dùng table.count để biết

snoopy
13-11-2003, 09:41
select count(*),* from County
mình đã thử query kiểu này rồi và sql báo lổi:

Server: Msg 8118, Level 16, State 1, Line 1
Column 'County.CountyID' is invalid in the select list because it is not contained in an aggregate function and there is no GROUP BY clause.
Server: Msg 8118, Level 16, State 1, Line 1
Column 'County.Name' is invalid in the select list because it is not contained in an aggregate function and there is no GROUP BY clause.
Server: Msg 8118, Level 16, State 1, Line 1
Column 'County.Code' is invalid in the select list because it is not contained in an aggregate function and there is no GROUP BY clause.

CountyID, Name, Code là những field của table County. Các bạn có bít cách khắc phục lổi này k chỉ giúp mình nha..

1011
13-11-2003, 09:42
Nếu dùng DataReader:


strSQL = "SELECT * FROM Country ORDER BY Name";
SqlDataReader dr ;
SqlCommand objCmd = new SqlCommand(strSQL, Connection);

objCmd.Connection.Open();
dr = objCmd.ExecuteReader();
int iCount = 0;
if(dr.Read())
{
iCount += 1;
...
}


Nếu dùng DataSet:


int iCount = 0;
strSQL = "SELECT * FROM Country ORDER BY Name";
SqlDataAdapter sqlAdp;
DataSet ds = new DataSet();
sqlAdp = new SqlDataAdapter(strSQL, Connection);
sqlAdp.Fill(ds);
iCount = ds.Tables[0].Rows.Count;


Connection: chuỗi connect đến Database
iCount: số record của câu query của bạn.