新しい値をその列に連結して列を更新するクエリを実行しています。
以下のような 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