Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TSQL: if statement inside a select insert

I have this structure inside a function:

INSERT INTO @TheTable
    SELECT DISTINCT

        @Number AS Number,

        @Name AS Name

    FROM MYTABLE 
    WHERE id = @id

I need to add to this structure the result of executing another function and I need your help to do so.

Below the @Name AS Name, line I should add something like this

IF (dbo.anotherFunction(@id)==1) 
@NewVisitor AS NewVisitor
ELSE
@NewVisitor AS NoNewVisitor

How can I translate this into TSQL??

Thanks a million!

like image 432
user712027 Avatar asked Feb 22 '23 17:02

user712027


1 Answers

Guessing this is what you want...

INSERT INTO @TheTable
    SELECT DISTINCT
        @Number AS Number,
        @Name AS Name,
        case when (dbo.anotherFunction(@id)=1) then @NewVisitor else null end as NewVisitor,
        case when (dbo.anotherFunction(@id)<>1) then @NewVisitor else null end AS NoNewVisitor
    FROM MYTABLE 
    WHERE id = @id
like image 112
Beth Avatar answered Feb 27 '23 06:02

Beth