Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set variable to NULL if not found in query statement

I have following code

DECLARE @a INT

SET @a = 1

SELECT TOP 1
    @a = id
FROM
    test
WHERE
    name = 'notexist'

SELECT @a

variable @a will still have 1 value if the SELECT statement doesn't find any row, is it possible to set the @a variable to null if the SELECT statement doesn't find any row without adding SET @a = NULL before SELECT statement?

like image 690
warheat1990 Avatar asked Jan 30 '26 12:01

warheat1990


2 Answers

Try this

SELECT TOP 1
    @a = id
FROM
    test
WHERE
    name = 'notexist'

If @@rowcount = 0
set @a = NULL

or

set @a = case when @@rowcount = 0 then null else @a end

But its better to avoid the initialization of 1. By default it will be NULL

like image 197
Pரதீப் Avatar answered Feb 02 '26 13:02

Pரதீப்


Assign value this way

SET @a = (
SELECT TOP 1
    id
FROM
    test
WHERE
    name = 'notexist'
)

SELECT @a
like image 42
Mukesh Kalgude Avatar answered Feb 02 '26 12:02

Mukesh Kalgude