找出SQLCommand查询中是否有任何行

时间:2010-11-09 18:15:14

标签: asp.net sql

我有一些像这样的代码

Dim conn As SqlConnection = New SqlConnection("server='h'; user id='w'; password='w'; database='w'; pooling='false'") 

conn.Open() 

Dim query As New SqlCommand("DECLARE @investor varchar(10), @sql varchar(1000) Select @investor = 69836 select @sql = 'SELECT * FROM OPENQUERY(db,''SELECT * FROM table WHERE investor = ''''' + @investor + ''''''')' EXEC(@sql)", conn) 

dgBookings.DataSource = query.ExecuteReader 
dgBookings.DataBind() 

我需要添加If语句,基本上说SQLCommand query是否返回没有行然后显示特定标签

可以这样做吗?

由于

2 个答案:

答案 0 :(得分:2)

当您致电SqlDataReader时,您将被ExecuteReader()返回,并且SqlDataReaderHasRows属性,您可以查看。

Dim oDR As SqlDataReader = query.ExecuteReader()

If oDR.HasRows Then
  lblNoRows.Visible = False
Else
  lblNoRows.Visible = True
End IF

答案 1 :(得分:2)

尝试:

Dim conn As SqlConnection = New SqlConnection("server='h'; user id='w'; password='w'; database='w'; pooling='false'") 

conn.Open() 

Dim query As New SqlCommand("DECLARE @investor varchar(10), @sql varchar(1000) Select @investor = 69836 select @sql = 'SELECT * FROM OPENQUERY(db,''SELECT * FROM table WHERE investor = ''''' + @investor + ''''''')' EXEC(@sql)", conn) 

Dim rdr as SqlDataReader
rdr = query.ExecuteReader()

if (rdr.HasRows) then
   dgBookings.DataSource = rdr
   dgBookings.DataBind() 
else
    .....
end if

显然你可以确保清理/处理对象,所以这只是为了展示HasRows;)