开发者

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

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜