0

很多时候,在项目中,我们将一个 ID 列表从 UI 传递到存储过程。大多数解决方案都基于创建 sql 字符串拆分函数,该函数创建临时表并使用临时表执行一些内部连接器。等

有没有人有创建 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?

请分享你的智慧

4

1 回答 1

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

看起来很简单……你觉得呢?

于 2012-12-05T15:19:27.447 回答