Search code examples
sqlsql-serversql-function

SQL IF-Statment within funciton


I've been working with SQL lately to make ends meet with my programming. I am trying to create a function which does a select, and if it views any duplicates (>1) of the same Analyte, it will create a string.

For example, If the select statement pulls back apples, oranges, peanuts, grapes, grapes, peaches, oranges, pineapple I will obtain a string of oranges,grapes. However if the there are no duplicates, the system breaks with an error since I'm trying to use a sub-string call on nothing.

How can I use an IF-Statment to make it pass back "NORECS" if result is still empty, and to use the sub-string functionality if it is not empty?

Working code which breaks if select doesn't pull duplicates:

Declare @result varchar(1000)

set @result = ''

select @result = @result + R.ANALYTE + ','
 FROM results R (NOLOCK)    
    left join tests T (NOLOCK) on (T.testcode = R.testcode)

where 
T.SHOW='Y' and R.SA='Show'
and R.ID = 3094083
group by R.ANALYTE
having COUNT(*)>1

select substring(@result, 1, len(@result) - 1) AS MissingAnas

Attempted IF-Statement which does the "Else" regardless.

    Declare @result varchar(1000)

    set @result = ''

    select @result = @result + R.ANALYTE + ','
     FROM results R (NOLOCK)    
        left join tests T (NOLOCK) on (T.testcode = R.testcode)

    where 
    T.SHOW='Y' and R.SA='Show'
    and R.ID = 3094083
    group by R.ANALYTE
    having COUNT(*)>1

    if (Count(@result)>1)
    Begin
    select substring(@result, 1, len(@result) - 1) AS MissingAnas
    End
    Else
    Begin
    set @result = 'NORECS'
    select @result AS MissingAnas
    End

Solution

  • Use RETURN Statement in below format :
    
    Declare @result varchar(1000)
    
    set @result = ''
    
    select @result = @result + R.ANALYTE + ','
     FROM results R (NOLOCK)    
        left join tests T (NOLOCK) on (T.testcode = R.testcode)
    
    where 
    T.SHOW='Y' and R.SA='Show'
    and R.ID = 3094083
    group by R.ANALYTE
    having COUNT(*)>1
    
    if (Count(@result)>1)
    Begin
       SET @result = substring(@result, 1, len(@result) - 1) 
    End
    Else
    Begin
       SET @result = 'NORECS'
    End
    
    SELECT @result