这里应该使用表值参数吗?

时间:2013-04-16 14:50:49

标签: sql-server-2008 c#-3.0

我有以下查询:

 @"UPDATE students SET IsDeleted = 1 WHERE StudentId IN (
         SELECT StudentId FROM Class where PassId IN (
              SELECT Id FROM ClassValueTable WHERE IsDeleted <> 1" 
                + activeIds)))";

其中activeIds =某些数字的字符串,例如:1,2,3,4 ......

我想将此查询转换为存储过程。我的问题是将activeIds作为参数传递给此存储过程的最佳方法是什么?

*代码在C#中,我正在使用SQL Server 2008

1 个答案:

答案 0 :(得分:3)

是的,使用表值参数。首先创建一个类型:

CREATE TYPE dbo.StudentIDs(ID INT PRIMARY KEY);

现在您的程序可以使用此功能(请注意,我已将嵌套的IN查询更改为正确的连接):

CREATE PROCEDURE dbo.MarkStudentsAsDeleted
  @IDs dbo.StudentIDs READONLY
AS
BEGIN
  SET NOCOUNT ON;

  UPDATE s SET IsDeleted = 1
    FROM dbo.Students AS s
    INNER JOIN dbo.Class AS c
    ON s.StudentId = c.StudentId
    INNER JOIN dbo.ClassValueTable AS ct
    ON c.PassId = ct.Id
    WHERE ct.IsDeleted <> 1
    AND EXISTS (SELECT 1 FROM @IDs WHERE StudentID = s.StudentID);
END 
GO

您的C#代码将传入DataTable,但是您已经汇编了activeIds集合,而不是逗号分隔列表。

DataTable dt = new DataTable();
dt.Columns.Add("ID", typeof(int));
dt.Rows.Add(1);
dt.Rows.Add(2);
dt.Rows.Add(3);
dt.Rows.Add(4);

... open connection etc. ...

SqlCommand cmd = new SqlCommand("dbo.MarkStudentsAsDeleted", conn);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter tvp1 = cmd.Parameters.AddWithValue("@IDs", dt);
tvp1.SqlDbType = SqlDbType.Structured;
cmd.ExecuteNonQuery();

... close, dispose, etc. ...

如果您想坚持将字符串传递给存储过程,则需要使用split函数。例如:

CREATE FUNCTION dbo.SplitInts
(
   @List       VARCHAR(MAX),
   @Delimiter  VARCHAR(255) = ','
)
RETURNS TABLE
WITH SCHEMABINDING 
AS
  RETURN 
  (  
    SELECT [value] = y.i.value('(./text())[1]', 'int')
    FROM 
    ( 
      SELECT x = CONVERT(XML, '<i>' 
        + REPLACE(@List, @Delimiter, '</i><i>') 
        + '</i>').query('.')
    ) AS a CROSS APPLY x.nodes('i') AS y(i)
  );
GO

现在您的存储过程可以是:

CREATE PROCEDURE dbo.MarkStudentsAsDeleted
  @IDs VARCHAR(MAX)
AS
BEGIN
  SET NOCOUNT ON;

  UPDATE s SET IsDeleted = 1
    FROM dbo.Students AS s
    INNER JOIN dbo.Class AS c
    ON s.StudentId = c.StudentId
    INNER JOIN dbo.ClassValueTable AS ct
    ON c.PassId = ct.Id
    WHERE ct.IsDeleted <> 1
    AND EXISTS (SELECT 1 FROM dbo.SplitInts(@IDs, ',') WHERE Item = s.StudentID);
END 
GO