这是一个老问题,但我想出了一个优雅的解决方案,我喜欢重复使用它,我认为其他人都会发现它很有用。
首先,您需要在 SqlServer 中创建一个 FUNCTION,它接受一个分隔输入并返回一个表,其中项目被拆分为记录。
下面是代码:
ALTER FUNCTION [dbo].[Split]
(
@RowData nvarchar(max),
@SplitOn nvarchar(5) = ','
)
RETURNS @RtnValue table
(
Id int identity(1,1),
Data nvarchar(100)
)
AS
BEGIN
Declare @Cnt int
Set @Cnt = 1
While (Charindex(@SplitOn,@RowData)>0)
Begin
Insert Into @RtnValue (data)
Select
Data = ltrim(rtrim(Substring(@RowData,1,Charindex(@SplitOn,@RowData)-1)))
Set @RowData = Substring(@RowData,Charindex(@SplitOn,@RowData)+1,len(@RowData))
Set @Cnt = @Cnt + 1
End
Insert Into @RtnValue (data)
Select Data = ltrim(rtrim(@RowData))
Return
END
您现在可以执行以下操作:
Select Id, Data from dbo.Split('123,234,345,456',',')
不用担心,这不会受到 Sql 注入攻击。
接下来编写一个使用逗号分隔数据的存储过程,然后您可以编写一个使用此拆分函数的 sql 语句:
CREATE PROCEDURE [dbo].[findDuplicates]
@ids nvarchar(max)
as
begin
select ID
from SomeTable with (nolock)
where ID in (select Data from dbo.Split(@ids,','))
end
现在您可以围绕它编写一个 C# 包装器:
public void SomeFunction(List<int> ids)
{
var idsAsDelimitedString = string.Join(",", ids.Select(id => id.ToString()).ToArray());
// ... or however you make your connection
var con = GetConnection();
try
{
con.Open();
var cmd = new SqlCommand("findDuplicates", con);
cmd.Parameters.Add(new SqlParameter("@ids", idsAsDelimitedString));
var reader = cmd.ExecuteReader();
// .... do something here.
}
catch (Exception)
{
// catch an exception?
}
finally
{
con.Close();
}
}