想从SQL表中搜索布尔结果C#(Would like a Boolean result from a SQL table search C#)
我正在尝试使用C#SQL搜索,然后获取关于是否找到该项目的布尔结果。 我有搜索语句工作但不是布尔结果部分。
EX:如果我有一个名为@Names的列的表,其名称为A,B,C,但我搜索名称D,如何或者我可以得到一个布尔结果返回并在布尔变量中保存false。
I am trying to use a C# SQL search and then get a Boolean result on whether or not the item was found. I have the search statement working but not the Boolean result portion.
EX: If i have a table with a column called @Names with the names, A,B,C but i search for Name D, how or can i get a Boolean result to come back and save false in a Boolean variable.
最满意答案
你可以尝试这种方法:
string query = @" select case when exists ( select 1 from MyTable where Name='D' -- This is the condition you are checking ) then 1 else 0 end"; bool exists; using(var command = new SqlCommand(query, connection)) { exists = Convert.ToBoolean(command.ExecuteScaler()); }您现在可以使用ExecuteScalar方法,并将结果转换为bool以获取查询结果。
You can try this approach:
string query = @" select case when exists ( select 1 from MyTable where Name='D' -- This is the condition you are checking ) then 1 else 0 end"; bool exists; using(var command = new SqlCommand(query, connection)) { exists = Convert.ToBoolean(command.ExecuteScaler()); }You can now use the ExecuteScalar method, and cast the result to bool for the result of your query.
更多推荐
发布评论