Expresiones booleanas en SQL Select list
Quiero crear una selección SQL para hacer una prueba unitaria en MS SQL Server 2005. La idea básica es la siguiente:
Seleccione 'Nombre de prueba', foo = 'Resultado' desde el bar donde baz = (algunos criterios)
La idea es que, si el valor de la columna "foo" es "Resultado", entonces obtendría un valor de true/1; si no lo es, obtendría false/0.
Desafortunadamente, a T-SQL no le gusta la expresión; se atraganta con el signo igual.
¿ Hay alguna forma de evaluar una expresión en la lista SQL select? ¿y obtener un resultado retornable? (O alguna otra forma de lograr las pruebas unitarias que quiero?)
EDITAR: 3 genial, respuestas, todo construido alrededor del CASO. Aceptaré la de Feihtthief ya que tiene menos reputación y por lo tanto la necesita más. :-) Gracias a todos.
4 answers
Utilice la construcción case:
select 'Test Name',
case when foo = 'Result' then 1 else 0 end
from bar where baz = (some criteria)
También vea la documentación del CASO Transact-SQL de MSDN.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-10-02 20:25:42
SELECT 'TestName',
CASE WHEN Foo = 'Result' THEN 1 ELSE 0 END AS TestResult
FROM bar
WHERE baz = @Criteria
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-01-30 22:30:44
CASO de uso:
SELECT 'Test Name' [col1],
CASE foo
WHEN 'Result' THEN 1
ELSE 0
END AS [col2]
FROM bar
WHERE baz = (some criteria)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-01-30 22:33:14
También puedes usar:
select
'Test Name',
iif(foo = 'Result', 1, 0)
from bar
where baz = (some criteria)
Sé que esto fue preguntado hace un tiempo, pero espero que esto ayude a alguien por ahí.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-09-12 00:48:31