2011-08-23 35 views
0

我有一个表说emp,因为我没有任何值。如果我使用此查询 在asp.net编码“选择EMP *”象下面这样:如何知道Sql Server中的表中是否没有值

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(); 

在EMP表中,我没有任何empname作为阿卜杜勒,当我这样做它应该显示一些错误, 怎么做?

回答

2

也许你的问题是你的代码是错误,因为你没有在你创建的命令上执行DataReader。见下:

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(); 
2

假设你在存储过程中的工作,看看@@ROWCOUNT

否则,你得给我们提供更多的信息。你想在哪里显示这个错误?


对于那些不能按照链接,它提供了使用@@ ROWCOUNT检查,如果一个UPDATE语句工作的例子。

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

我在ASP.NET编码中使用查询(select * from emp)... –

3

为什么不只是做:

select count(*) from emp 

,看看你得到超过0的记录?

0
CREATE TABLE #T (int_f int) 

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

如果您查询没有行的表,它将只返回0行。它不会返回错误。

相关问题