How to check if a select query result is NULL in SQL Server

守給你的承諾、 提交于 2019-12-24 03:10:23

问题


in SQL Server , how do I verify if a query has returned NULL and run blocks depending on it . e.g. in query 1 , I want to check if count(*) is not null and then check if it has >0 . Should I use if exists here ?

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

In Oracle one can say IF INSERTING THEN or IF updating THEN or if deleting then run a certain block of code based on a column . how do we do it in SQL Server ? Please see Oracle code below .

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

回答1:


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

You can't get null from a count so if you do a check for 0 that's practically the equivalent.

The else if checks for anything that the count returns

you could also use an IF EXISTS

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



回答2:


If you are writing a trigger you generally don't bother checking if anything exists in the pseduo table, you just write the code based off the pseudo table. Also note that oracle triggers perform row by row and SQL Server triggers are called once, with possibly mutliple records in psuedo tables.

So you'd do something like this in your trigger:

INSERT INTO AnotherTable (Col1,Col2) SELECT Col1,Col3 FROM INSERTED

INSERTED is a pseudo table. It contains all records inserted (or updated). There might be 0,1, or many records in here.

If there are zero records, nothing will be inserted by this code.

Back to your original question, the best way to check if there are no rows is to do this:

IF EXISTS (SELECT 1 FROM INSERTED)
BEGIN
-- Some Code
END

Or, in a trigger, you can simply specify the trigger does not fire at all for UPDATE or INSERT.




回答3:


select FOUND_ROWS();

will return no. of records selected by select query.



来源:https://stackoverflow.com/questions/25323802/how-to-check-if-a-select-query-result-is-null-in-sql-server

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!