开发者

How do/can I run a select SQL statement inside an if?

开发者 https://www.devze.com 2023-01-04 20:45 出处:网络
I\'m having trouble finding the syntax for a statement (or whether or not it\'s even possible). We\'re running SQL Server 2005, and I\'d like to do something like:

I'm having trouble finding the syntax for a statement (or whether or not it's even possible).

We're running SQL Server 2005, and I'd like to do something like:

IF ((SELECT count(*) FROM mytable WHERE userid = 'myid' AND value = 3) < 1) then INSERT INTO mytable VALUES ('myid', 3)

开发者_开发知识库

Any suggestions? Thanks


IF ((SELECT count(*) FROM mytable WHERE userid = 'myid' AND value = 3) < 1)
BEGIN
    INSERT INTO mytable VALUES ('myid', 3)
END

IF/ELSE reference

or you could use NOT EXISTS

IF NOT EXISTS (SELECT * FROM mytable WHERE userid = 'myid' AND value = 3)


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


You could try this to do it in a single statement:

INSERT INTO mytable
SELECT 'myid', 3
WHERE (SELECT count(*) FROM mytable WHERE userid = 'myid' AND value = 3) < 1
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号