Vaibhav Jain
Vaibhav Jain

Reputation: 34407

CASE WHEN in SQL Server

 SET @Result = @KriteriumTekst + 
               CASE @Operator 
                  WHEN 'LT' THEN '<'
                  WHEN 'GT' THEN '>'
                  WHEN 'NE' THEN '<>'
                  WHEN 'EQ' THEN '='
               + @Verdi + 
               CASE @Tilstand 
                  WHEN 'OG' THEN 'AND'
                  WHEN 'ELLER' THEN 'OR'

This statement is not compiling, what could be the issue.

Upvotes: 2

Views: 228

Answers (4)

David Hedlund
David Hedlund

Reputation: 129792

As has been pointed out in comments, your cases needs to be terminated with END

Other than that, if @Operator is "LT" and @Tilstand is "OG", you'd have a result that looks like

@KriteriumTekst + '<' + @Verdi + 'OG'

Given values to @KriteriumTekst and @Verdi, you may end up with something like

@Result = '1<5OG'

It is difficult to see what you would want to do with that string.

Upvotes: 1

Alberto De Caro
Alberto De Caro

Reputation: 5213

Each CASE requires the END keyword (MSDN reference):

declare @result nvarchar(256)
declare @KriteriumTekst nvarchar(256)
declare @Operator nvarchar(256)
declare @Verdi nvarchar(256)
declare @Tilstand nvarchar(256)

set @KriteriumTekst = 'Tekst '
set @Operator = 'LT'
set @Verdi = 'Verdi '
set @Tilstand = 'OG'
 SET @Result= @KriteriumTekst+CASE @Operator WHEN 'LT' THEN '<'
                                        WHEN 'GT' THEN '>'
                                        WHEN 'NE' THEN '<>'
                                        WHEN 'EQ' THEN '=' END
                    +@Verdi+ CASE @Tilstand WHEN 'OG' THEN 'AND'
                                            WHEN 'ELLER' THEN 'OR' END
select @result

Upvotes: 0

Martin
Martin

Reputation: 40335

You need to terminate the case statement:

SET @Result= @KriteriumTekst+CASE @Operator WHEN 'LT' THEN '<'
                                        WHEN 'GT' THEN '>'
                                        WHEN 'NE' THEN '<>'
                                        WHEN 'EQ' THEN '='
                                        END
                    +@Verdi+ CASE @Tilstand WHEN 'OG' THEN 'AND'
                                            WHEN 'ELLER' THEN 'OR'
                                            END

Upvotes: 0

ypercubeᵀᴹ
ypercubeᵀᴹ

Reputation: 115530

You are miising the END of the CASE expressions:

 SET @Result= @KriteriumTekst+CASE @Operator WHEN 'LT' THEN '<'
                                        WHEN 'GT' THEN '>'
                                        WHEN 'NE' THEN '<>'
                                        WHEN 'EQ' THEN '='
                              END

                    +@Verdi+ CASE @Tilstand WHEN 'OG' THEN 'AND'
                                            WHEN 'ELLER' THEN 'OR'
                             END

Upvotes: 4

Related Questions