简体   繁体   中英

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

I am having one table say emp, in that 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?

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.

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();
CREATE TABLE #T (int_f int)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM