我在DB中有一个表,其中存在一些记录。
当我添加新记录时,如果记录存在于DB中,我需要按“名称”列进行检查。如果这样的记录不存在 - 那么添加它,如果存在 - 然后更新。我这样想:
USE [TestDB]
GO
DECLARE @daily nvarchar = 'DailySummaryEmailProcessor'
IF NOT EXISTS ( SELECT *
FROM [dbo].Crons
WHERE name = @daily)
BEGIN
INSERT INTO [dbo].Crons (CronJobID, Name, Description)
VALUES()
END
ELSE
BEGIN
UPDATE [dbo].Crons
SET
WHERE
END
答案 0 :(得分:2)
MERGE应符合您的要求MERGE (Transact-SQL):
MERGE Crons AS target
USING (SELECT @Name) AS source (Name)
ON (target.Name = source.Name)
WHEN MATCHED THEN
UPDATE SET target.Name = source.Name
WHEN NOT MATCHED
INSERT INTO Crons (Name) VALUES (source.Name)
OUTPUT $action, deleted.Name, inserted.Name
答案 1 :(得分:1)
问题是你永远不会声明变量@dialy
的大小试试这个,看看你得到了什么
DECLARE @daily nvarchar = 'DailySummaryEmailProcessor'
SELECT @daily
看起来你需要做INSERT .. UPDATE ..查看MERGE
语句
https://docs.microsoft.com/en-us/sql/t-sql/statements/merge-transact-sql?view=sql-server-2017
编辑:
哦..你的标签里有MySQL
。我的答案专门针对SQL Server
。