我正在进行一个查询,我希望通过将新值连接到该列来更新列 我已经制作了如下的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
答案 0 :(得分:0)
第@sql = 'UPDATE...
行应为SET @sql = 'UPDATE...
此外,您需要将@id
参数传递给@sql,就像这样..
EXEC sp_executesql @sql, N'@id int', @id
您可以在sp_executesql
:http://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
只删除了前导逗号。