if语句在sql中使用查询

Mr.*_*r.J 2 sql sql-server stored-procedures if-statement sql-server-2000

我想问一下如何使用IF statementin 进行条件检查SQL,类似下面的例子.

if (select* from table where id = @id) = 1 --if this returns a value

insert statement


else

update statement

go
Run Code Online (Sandbox Code Playgroud)

或类似的东西,如使用存储过程...

if (exec SP_something 2012, 1) = 0 

insert statement

else

update stement
Run Code Online (Sandbox Code Playgroud)

或者可能在sql语句中使用UDF,如...

if (select dbo.udfSomething(1,1,2012)) = 0 

insert statement

else

update statement

go
Run Code Online (Sandbox Code Playgroud)

Muh*_*ani 5

(1)使用语句块

IF 
(SELECT COUNT(*) FROM Production.Product WHERE Name LIKE 'Touring-3000%' ) > 5
BEGIN
   PRINT 'There are 5 Touring-3000 bikes.'
END
ELSE 
BEGIN
   PRINT 'There are Less than 5 Touring-3000 bikes.'
END ;
Run Code Online (Sandbox Code Playgroud)

(2)调用存储过程.

DECLARE @compareprice money, @cost money 
EXECUTE Production.uspGetList '%Bikes%', 700, 
    @compareprice OUT, 
    @cost OUTPUT
IF @cost <= @compareprice 
BEGIN
    PRINT 'These products can be purchased for less than 
    $'+RTRIM(CAST(@compareprice AS varchar(20)))+'.'
END
ELSE
    PRINT 'The prices for all products in this category exceed 
    $'+ RTRIM(CAST(@compareprice AS varchar(20)))+'.'
Run Code Online (Sandbox Code Playgroud)

更多例子:

MSDN 1 MSDN 2