Search code examples
sqlsql-serversql-server-2008

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?


Solution

  • Assign value this way

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