gpt4 book ai didi

sql - if语句在sql中使用查询

转载 作者:行者123 更新时间:2023-12-04 19:19:11 24 4
gpt4 key购买 nike

我想问一下如何在SQL中使用IF语句进行条件检查,比如下面的例子..

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

insert statement


else

update statement

go

或类似使用存储过程...

if (exec SP_something 2012, 1) = 0 

insert statement

else

update stement

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

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

insert statement

else

update statement

go

最佳答案

(1) 使用语句 block

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 ;

(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)))+'.'

更多示例:

MSDN 1 MSDN 2

关于sql - if语句在sql中使用查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14513314/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com