我无法找到语句的语法(或者它是否可能)。
我们正在运行SQL Server 2005,我想做类似的事情:
IF ((SELECT count(*) FROM mytable WHERE userid = 'myid' AND value = 3) < 1) then INSERT INTO mytable VALUES ('myid', 3)
有什么建议吗?感谢
答案 0 :(得分:3)
IF ((SELECT count(*) FROM mytable WHERE userid = 'myid' AND value = 3) < 1)
BEGIN
INSERT INTO mytable VALUES ('myid', 3)
END
或者您可以使用NOT EXISTS
IF NOT EXISTS (SELECT * FROM mytable WHERE userid = 'myid' AND value = 3)
答案 1 :(得分:1)
DECLARE @COUNT int
SET @COUNT=(SELECT count(*) FROM mytable WHERE userid = 'myid' AND value = 3)
IF (@COUNT < 1)
BEGIN
INSERT INTO mytable VALUES ('myid', 3)
END
答案 2 :(得分:1)
您可以尝试在单个语句中执行此操作:
INSERT INTO mytable
SELECT 'myid', 3
WHERE (SELECT count(*) FROM mytable WHERE userid = 'myid' AND value = 3) < 1