2010-08-04 20 views
8

Me gustaría saber cómo puedo usar las variables locales en las declaraciones CASE en SQL?SQL CASE y variables locales

Este script me da un error:

DECLARE @Test int; 
    DECLARE @Result char(10); 
    SET @Test = 10; 

    CASE @Test 
    WHEN @Test = 10 
    THEN SET @Result='OK test' 
    END 
    Print @Result; 

utilizo MS SQL 2008.

+0

¿Qué base de datos está usando? – Oded

+0

MS SQL 2008 MS SQL 2008 – GibboK

+0

¿Han soltado la parte "Servidor" del nombre? ;-P –

Respuesta

19

Dos maneras de utilizar CASE en este escenario con MSSQL

DECLARE 
    @test int, 
    @result char(10) 

SET @test = 10 

SET @result = CASE @test 
    WHEN 10 THEN 
     'OK test' 
    ELSE 
     'Test is not OK' 
END 

PRINT @result; 

SET @result = CASE 
    WHEN @test = 10 THEN 
     'OK test' 
    ELSE 
     'Test is not OK' 
END 

PRINT @result 
1

En SQL Server lo escribiría así:

DECLARE @Test int; 
DECLARE @Result char(10); 
SET @Test = 10; 

SET @Result = CASE @Test 
WHEN 10 
THEN 'OK test' 
END 
Print @Result; 

La cláusula WHEN no lo hace tiene @Test = 10, ya que la variable @Test se indica en la cláusula CASE.

Consulte la documentación CASE para SQL Server.

+0

Esto no funciona en mi SQL 2005 db. (sintaxis incorrecta cerca de la palabra clave 'Caso'). (Tenía la misma solución, pero no funcionó). – Tobiasopdenbrouw

+0

da errores – GibboK

+0

La sintaxis aquí es incorrecta. No puede usar una declaración de caso como una instrucción if. –

0

CASO CUANDO @test 10 ENTONCES

0
DECLARE @Test int; 
SET @Test = 10; 

SELECT 
CASE @Test 
WHEN 10 
THEN 'OK test' 
END 

Para el servidor SQL 2005

+0

La respuesta de anishmarokey es un poco más limpia ya que conserva su variable @result. – Tobiasopdenbrouw

2

intente esto:

DECLARE @Test int; 
DECLARE @Result char(10); 
SET @Test = 10; 

select @Result= 
CASE @Test 
WHEN 10 THEN 'OK test' 
END 

Print @Result; 
Cuestiones relacionadas