在项目中,我们多次将UI列表传递给存储过程。大多数解决方案都基于创建sql字符串拆分函数,这些函数创建临时表并使用临时表执行某些内部联接器。 E.T。
是否有人有创建CLR SQL UDT的经验,我们可以将一些StringList传递给用户proc
StringList stringList = new StringList();
stringList.Add("ID1");
stringList.Add("ID2");
stringList.Add("ID3");
SqlCommand cmd = new SqlCommand("SelectDataByIDs");
cmd.Parameters.Add(new SqlParameter("list", SqlDbType.Udt){ Value = stringList});
并在SQL中使用
SELECT * FROM DataTable
WEHRE DataId in @stringList -- or inner join?
请分享你的智慧
答案 0 :(得分:1)
这是我为我的案子所做的:
--declare type
CREATE TYPE StringIDList AS TABLE
( StringId NVARCHAR(8) NOT NULL PRIMARY KEY )
go
--test function
CERATE PROCEDURE SelectListValue
( @ids [dbo].[StringIDList] readonly )
AS
BEGIN
SELECT * FROM @ids WHERE StringId <> '30'
END
C#代码
SqlConnection conn = new SqlConnection(@"Data Source=.\SQLEXPRESS2012;Initial
Catalog=db;Integrated Security=true");
conn.Open();
List<SqlDataRecord> records = new List<SqlDataRecord>();
var rec = new SqlDataRecord(new SqlMetaData("stringid", SqlDbType.NVarChar, 8));
rec.SetValue(0, "10");
records.Add(rec);
rec = new SqlDataRecord(new SqlMetaData("stringid", SqlDbType.NVarChar, 8));
rec.SetValue(0, "30");
records.Add(rec);
var cmd = new SqlCommand("SelectListValue");
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = conn;
var param = new SqlParameter("@ids", SqlDbType.Structured);
param.Direction = ParameterDirection.Input;
param.TypeName = "StringIDList";
param.Value = records;
cmd.Parameters.Add(param);
var reader = cmd.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(reader.GetString(0));
}
控制台输出
10
看起来非常直接......你怎么看?