开发者

How to know whether there is no values in a Table in Sql Server

I am having one table say emp, in tha开发者_如何学JAVAt i dont have any values. If i using this query "select * from emp" in the asp.net coding like below:

con.Open();
String str="select * from emp where empname="Abdul";
cmd=new SqlCommand(str,con);
SqlDataReader dr=new SqlDataReader();
while(dr.Read())
{
  textBox1.text=dr[0].ToString();
  textBox2.text=dr[0].ToString();
  textBox3.text=dr[0].ToString();
}
con.Close();

In emp tables, i dont have any empname as abdul, When i am doing this it should show some errors, how to do it?


Why not just do:

select count(*) from emp

and see if you get more than 0 records?


Perhaps your problem is that your code is wrong because you are not executing the DataReader on the Command you created. See below:

con.Open();
String str="select * from emp where empname="Abdul";
cmd=new SqlCommand(str,con);
SqlDataReader dr=new SqlDataReader(); //WRONG. See my version below
while(dr.Read())
{
  textBox1.text=dr[0].ToString();
  textBox2.text=dr[0].ToString();
  textBox3.text=dr[0].ToString();
}

con.Close();

con.Open();
String str="select * from emp where empname="Abdul";
cmd=new SqlCommand(str,con);
SqlDataReader dr=cmd.ExecuteReader(); //Correct way
while(dr.Read())
{
  textBox1.text=dr[0].ToString();
  textBox2.text=dr[0].ToString();
  textBox3.text=dr[0].ToString();
}
con.Close();


Assuming you're working in a stored procedure, take a look at @@ROWCOUNT

Otherwise, you'll have to give us a bit more information. Where are you trying to show this error?


For those that can't follow the link, it provides an example using @@ROWCOUNT to check if an UPDATE statement worked.

USE AdventureWorks2008R2;
GO
UPDATE HumanResources.Employee 
SET JobTitle = N'Executive'
WHERE NationalIDNumber = 123456789
IF @@ROWCOUNT = 0
PRINT 'Warning: No rows were updated';
GO


If you query a table with no rows, it will simply return 0 rows. It doesn't return an error.


CREATE TABLE #T (int_f int)

SELECT
  CASE WHEN EXISTS (
              SELECT 
                 1 
              FROM #T) THEN 'yes'
  ELSE 'No'
END
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜