|
分類:[.NET 全般]
アップデートとインサートを同時にするというサイトを見て いろいろ試行錯誤しているのですが、 複数のデータをアップデートとインサートしようとしたのですが うまくいきません。 どうすればよいのでしょうか?
IF OBJECT_ID(N'tempdb..#TBL', N'U') IS NOT NULL DROP TABLE #TBL;
WITH TBL (ID, NAME, FLAG) AS ( SELECT 5, 'SS', 0 UNION SELECT 5, 'S3G', 1 UNION SELECT 5, 'S4G', 1 UNION SELECT 5, 'S5G', 1 ) SELECT * INTO #TBL FROM ( SELECT * FROM TBL ) AS TBL
SELECT * FROM #TBL
/*==================================================*/ DECLARE @BumonCode Int = 5;
BEGIN TRY BEGIN TRANSACTION;
-------------------------------------------------- WITH INS (ID, NAME, FLAG) AS ( SELECT 5, 'SP', 0 UNION SELECT 5, 'SS', 0 UNION SELECT 5, 'S3G', 1 UNION SELECT 5, 'S4G', 0 UNION SELECT 5, 'S5G', 1 ) UPDATE #TBL SET #TBL.Flag = INS.FLAG FROM #TBL INNER JOIN INS ON INS.ID = #TBL.ID AND INS.NAME = #TBL.NAME IF @@ROWCOUNT = 0 INSERT INTO #TBL SELECT * FROM INS --------------------------------------------------
COMMIT TRANSACTION; SELECT 0 END TRY BEGIN CATCH ROLLBACK TRANSACTION; SELECT 1 END CATCH;
/*==================================================*/
SELECT* FROM #TBL
IF OBJECT_ID(N'tempdb..#TBL', N'U') IS NOT NULL DROP TABLE #TBL;
|