如何用动态SQL交换同一列中的两个值?

时间:2012-10-06 00:32:33

标签: sql-server sql-server-2008 stored-procedures swap dynamic-sql

我正在使用SQL Server 2008。

我有很多桌子,每张桌子都包含 ID 字段和 TheOrder 字段。

我想创建一个存储过程,它可以在 TheOrder 字段中交换两个记录的值。

我通过 ASP.NET 代码获取这些记录的 ID ,并将它们传递给存储过程。

但是因为我想在许多表上执行这个存储过程,我必须使用动态SQL并从 ASP.NET 代码传递表名。

我的存储过程代码为:

ALTER PROCEDURE [dbo].[SwapOrders]
    @TblName nvarchar(20)
    , @ID1 int
    , @ID2 int
AS
BEGIN
    DECLARE @ID1Str nvarchar(5)
    SET @ID1Str = CAST(@ID1 AS nvarchar)
    DECLARE @ID2Str nvarchar(5)
    SET @ID2Str = CAST(@ID2 AS nvarchar)
    DECLARE @Order1 nvarchar(5)
    DECLARE @Order2 nvarchar(5)
    DECLARE @Cmd nvarchar(100)
    /* Get orders */
    SET @Cmd = 'SELECT @Order1 = [TheOrder] FROM ' + @TblName + ' WHERE ID = ' + @ID1Str
    EXECUTE sp_executesql @Cmd, "@Order1 nvarchar(5) OUTPUT", @Order1 = [TheOrder]
    SET @Cmd = 'SELECT @Order2 = [TheOrder] FROM ' + @TblName + ' WHERE ID = ' + @ID2Str
    EXECUTE sp_executesql @Cmd, "@Order2 nvarchar(5) OUTPUT", @Order2 = [TheOrder]
    /* Update orders */
    SET @Cmd = 'UPDATE ' + @TblName + ' SET TheOrder = @Order2 WHERE ID = ' + @ID1Str
    EXECUTE sp_executesql @Cmd, "@Order2 nvarchar(5)", @Order2
    SET @Cmd = 'UPDATE ' + @TblName + ' SET TheOrder = @Order1 WHERE ID = ' + @ID2Str
    EXECUTE sp_executesql @Cmd, "@Order1 nvarchar(5)", @Order1
END
GO

当我测试此代码时, TheOrder 字段的两个值变为 NULL

有什么问题?

非常感谢您的帮助,对不起,我很抱歉。

1 个答案:

答案 0 :(得分:1)

See this working demo

代码在

之下
CREATE PROCEDURE [dbo].[SwapOrders]
  @TblName nvarchar(20),
  @ID1 int,
  @ID2 int
AS
set nocount on
DECLARE @Cmd nvarchar(max) =
 'set nocount on;
  update t
  set TheOrder = u.TheOrder
  from ' + quotename(@tblname) + 't
  join ' + quotename(@tblname) + 'u on
  u.id=case when t.id=@id1 then @id2 else @id1 end
  where t.id in (@id1,@id2);';
exec sp_executesql @cmd, N'@id1 int,@id2 int', @id1, @id2;
GO