通过String Concat执行更新时出错

时间:2013-04-12 12:32:54

标签: sql sql-server-2008

我正在进行一个查询,我希望通过将新值连接到该列来更新列 我已经制作了如下的SQL代码但是我收到了一个错误:

DECLARE @sql varchar(max), @Id INT, @Total_Service_Amount float,
@Total_Cancellation_Charge float, @Total float

SET @Id = 1
SET @Total_Service_Amount = 1
SET @Total_Cancellation_Charge = 2
SET @Total = @Total_Service_Amount + @Total_Cancellation_Charge

SET @sql = 'UPDATE [DBO].[Service_Amount] SET Request_Id = '''
+ CONCAT (Request_Id, CAST(@Id AS VARCHAR), ',') + ''',
Amount = ''' + CONCAT (Amount, CAST(@Total) AS VARCHAR), ',')
+ ''' WHERE Request_For_Id = (SELECT Request_For_Id FROM
[DBO].Request WHERE Id=@Id)' 

EXEC sp_executesql @sql

我想要如下结果: 前:

  

Id | Request_Id |量

     

1 | 1,2,3,4 | 200,300,22,22

在:

  

Id | Request_Id |量

     

1 | 1,2,3,4,5 | 200,300,22,22,12

     

解决方案:

DECLARE @sql nvarchar(max), @Id INT, @Total_Service_Amount float, @Total_Cancellation_Charge float, @Total float, @beforeId varchar(500), @beforeAmount varchar(max)
SET @Id = 1
select @Total_Service_Amount = 1
select @Total_Cancellation_Charge = 2
select @Total = @Total_Service_Amount + @Total_Cancellation_Charge


SELECT @beforeId = Request_Id FROM [DBO].[Service_Amount] WHERE Request_For_Id = (SELECT Request_For_Id FROM [DBO].Request WHERE Id= @Id)

SELECT @beforeAmount = Amount FROM [DBO].[Service_Amount] WHERE Request_For_Id = (SELECT Request_For_Id FROM [DBO].Request WHERE Id= @Id)

SET @sql = 'UPDATE [DBO].[Service_Amount] SET Request_Id = ''' + @beforeId + ',' + convert(VARCHAR,@Id) +  ', Amount = ''' + @beforeAmount + ',' + convert(VARCHAR,@Total) + ''' WHERE Request_For_Id = (SELECT Request_For_Id FROM [DBO].Request WHERE Id=' + convert(VARCHAR,@Id) + ')' 
EXEC sp_executesql @sql, N'@id int', @Id

2 个答案:

答案 0 :(得分:0)

@sql = 'UPDATE...行应为SET @sql = 'UPDATE...

此外,您需要将@id参数传递给@sql,就像这样..

EXEC sp_executesql @sql, N'@id int', @id

您可以在sp_executesqlhttp://msdn.microsoft.com/en-us/library/ms188001.aspx

的文档中阅读更多内容

答案 1 :(得分:0)

如果你想将SELECT查询中的一堆字段粘合到一个字符串中,那就玩这种东西:

select STUFF(
               (SELECT ',',  Request_Id as [text()]
                FROM [DBO].[Service_Amount]
                FOR XML PATH ('')
               )
             , 1, 1, '')

这可以设置为变量
Set @my_var = (SELECT Stuff... )
并在UPDATE sql

中使用

FOR XML部分粘合在一起,STUFF只删除了前导逗号。