开发者

Returned ID from SELECT statement

I use in my Project the IfExistsTable function; in order to see the existence of a table.

For this purpose I use the Select statement as follows.

MASQLComm = New SqlCommand("SELECT COUNT(*) AS [RecCount] From sys.tables WHERE name Like '%" & tName & "%'", SQLConn)
RecCount = CInt(MASQLComm.ExecuteScalar)

After that I take开发者_StackOverflow the number which returned in RecCount. Until now the numbers was 1 and 0

And so I was turn the numbers in True or False.

Now suddenly the returned number is 2 which I can’t understand what it means.


Count return the number of rows in the table. You should not expect it to be 0 or 1 only.

You can argue that there can't be more then one table with one name, but the problem is that your query uses like '%TableName%'. So if you have table MyTable and BestTable, and you want to check if Table exits, the result of count will be 2, although there are is no table with such name.

You could update the select statement to look like this:

select case when exists(select * from sys.tables where name = 'TableName') then 1 else 0 end


The number represents the number of tables that match your like statement. For example, if you have the tables

  • Widgets
  • Products
  • WidgetsInProducts

And pass "Widgets" into your query, it's going to match both the table "Widgets" and "WidgetsInProducts". This is not the behavior you want.

To resolve this you need to do an exact match instead of a like as @Alex Aza demonstrated in his answer.


hi Lefteris Gkinis if you do not want to change your query you can check your RecCount variable accordingly say

if(RecCount == 0)
{
// code what you were using for false condition 
}
else
{
// you got atleast one record 
// and in RecCount  you have number of matching rows
}

by this kind of code you are able to show matched row count also.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜