if condition fails when var is null

  • hi

    every one here is my query

    create proc insertnewMailID(@GroupID int,@Name nchar(10),@Address nvarchar(50),@Email nchar(10))

    as

    declare @id as varchar(10)

    set @id = (select max(id)+1 from emails)

    if @id = NUll

    begin

    set @id = 1

    insert into emails values(@id,@GroupID,@Name,@Address,@Email,1)

    end

    else

    insert into emails values(@id,@GroupID,@Name,@Address,@Email,1)

    here set @id = (select max(id)+1 from emails) in these statement i am getting null value

    and if condition fails when value is null

    i checked

    declare @id as int

    set @id = (select max(id)+1 from emails)

    print @id here no value is diplyed

    so how can i execute if statment

    thanks in advance

    max

  • you declared id as varchar(10).How can you add 1 to it???

  • varchar i post that wrong

    i trired it for int ..

    thans for responce

  • got solutionn 🙂

    if @id is null

  • You cannot compare null with the an equal sign (=). When you check for null you have to use the is null or is not null operators. Take a look at the small script that shows that:

    declare @id int

    if @id = null

    select '@id=null was avluated as true'

    if @id <> null

    select '@id<&gtnull was avluated as true'

    if @id is not null

    select '@id is not null was avluated as true'

    if @id is null

    select '@id is null was avluated as true'

    An alternative is to use set ansi_null off, but I think that it is better to use the is null and is not null operators

    Adi

    --------------------------------------------------------------
    To know how to ask questions and increase the chances of getting asnwers:
    http://www.sqlservercentral.com/articles/Best+Practices/61537/

    For better answers on performance questions, click on the following...
    http://www.sqlservercentral.com/articles/SQLServerCentral/66909/

  • declare @id int

    if @id = null

    select '@id=null was avluated as true'

    if @id <> null

    select '@id<&gtnull was avluated as true'

    if @id is not null

    select '@id is not null was avluated as true'

    if @id is null

    select '@id is null was avluated as true'

    Heh this will make a nice Question-of-Day ... 🙂 you should submit it.

    [font="Arial"]---

    Mohit K. Gupta, MCITP: Database Administrator (2005), My Blog, Twitter: @SQLCAN[/url].
    Microsoft FTE - SQL Server PFE

    * Some time its the search that counts, not the finding...
    * I didn't think so, but if I was wrong, I was wrong. I'd rather do something, and make a mistake than be frightened and be doing nothing. :smooooth:[/font]

    How to ask for help .. Read Best Practices here[/url].

  • ANSI NULL OF goes bye-bye in next release, by the way.

    bye 🙂

Viewing 7 posts - 1 through 6 (of 6 total)

You must be logged in to reply to this topic. Login to reply