gpt4 book ai didi

sql-server - SQL Server中如何检查select查询结果是否为NULL

转载 作者:行者123 更新时间:2023-12-05 03:14:23 25 4
gpt4 key购买 nike

在 SQL Server 中,如何验证查询是否已返回 NULL 并根据它运行 block 。例如在查询 1 中,我想检查 if count(*) is not null 然后检查它是否有 >0 。我应该在这里使用 if exists 吗?

if select count(*) from tbl1 not is NULL then 
if select count(*) from tbl1 where count(*)>0 then
raiserror()
end if
end if

在 Oracle 中,可以说 IF INSERTING THENIF updating THENif deleting then 运行基于列的特定代码块.我们如何在 SQL Server 中做到这一点?请参阅下面的 Oracle 代码。

CREATE OR REPLACE TRIGGER tr_name
BEFORE DELETE OR INSERT OR UPDATE OF column1 ON tbl1
FOR EACH ROW
WHEN (NEW.column1 IS NOT NULL)
begin
IF INSERTING THEN
run some code like check if there are more than row in a table and if >0 then not allow any inserts
IF updating THEN
run some code
IF deleting THEN
run some code
end

最佳答案

DECLARE @ErrorMsg nvarchar(400)
IF (SELECT count(*) FROM tbl1) = 0
BEGIN
SET @ErrorMsg = 'You are returning nothing'
SELECT @ErrorMsg Err
RETURN
END
Else IF (SELECT count(*) FROM tbl1) >= 1
BEGIN
SET @ErrorMsg = 'You are returning something'
SELECT @ErrorMsg Err
RETURN
END

您不能从计数中得到 null,所以如果您检查 0,那实际上是等价的。

else if 检查计数返回的任何内容

你也可以使用 IF EXISTS

IF EXISTS   (
SELECT 1 FROM tbl1
)
BEGIN
SET @ErrorMsg = 'You are returning something'
SELECT @ErrorMsg Err
RETURN
END

关于sql-server - SQL Server中如何检查select查询结果是否为NULL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25323802/

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