c# - 如何在 WHERE 子句中使用字符串的每个单词?
问题描述
我遇到了一个问题,我在 SQL Server 2014 中有一个查询,查询结果应该基于WHERE
从 C# 获取字符串的子句CheckedListBox
。
我有这种形式的字符串(以下值仅作为示例):-
cat,dog,bird,duck
在数据库内部,记录如下所示:-
dog
cat-dog
cat-dog-duck
bird-dog-duck
等等...
我试过这个: -
DECLARE @animals nvarchar(max) = 'dog,bird,cat'
select x,y,z WHERE CHARINDEX(animals, replace(@animals,',',' ')) > 0
结果将仅显示带有ONE SINGLE VALUE
类似的行dog
cat
bird
但它不会显示带有类似等值的行dog-cat
dog-cat-bird
!它只显示@animals
字符串中包含一个单词的行。
如何从字符串中选择列中animals
包含一个或多个单词的所有行。@animals
提前致谢...
解决方案
您应该看一下表值参数,它可以让您将值表作为参数从 C# 发送到 SQL。您用“动物”制作一个表格,然后在您的存储过程中进行子选择。
请参阅下面链接中的示例代码,显示如何传递参数:
// Assumes connection is an open SqlConnection object.
using (connection)
{
// Create a DataTable with the modified rows.
DataTable addedCategories = CategoriesDataTable.GetChanges(DataRowState.Added);
// Configure the SqlCommand and SqlParameter.
SqlCommand insertCommand = new SqlCommand("usp_InsertCategories", connection);
insertCommand.CommandType = CommandType.StoredProcedure;
SqlParameter tvpParam = insertCommand.Parameters.AddWithValue("@tvpNewCategories", addedCategories);
tvpParam.SqlDbType = SqlDbType.Structured;
// Execute the command.
insertCommand.ExecuteNonQuery();
}
https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/sql/table-valued-parameters