你如何从 sql 语句返回一个常量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/304129/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 00:18:03  来源:igfitidea点击:

How do you return a constant from an sql statement?

sqlsql-servertsqlsql-server-2000

提问by wusher

How do I return a constant from an sql statement?

如何从 sql 语句返回常量?

For example how would I change the code below so "my message" would return if my (boolean expression) was true

例如,如果我的(布尔表达式)为真,我将如何更改下面的代码,以便“我的消息”返回

if (my boolean expression)
 "my message"
else
 select top 1 name from people;

I am using ms sql 2000

我正在使用 ms sql 2000

回答by Ned Batchelder

Did you try:

你试过了吗:

select 'my message';

回答by Kon

select "my message" as message

回答by Vinko Vrsalovic

I don't have MSSQL handy, but check the syntax for the CASE statement in case I got it wrong and also I'm not sure if the TOP 1 should go outside the case as I put it here or if it should go inside (ELSE TOP 1 name). The idea is:

我手边没有 MSSQL,但请检查 CASE 语句的语法,以防万一我弄错了,而且我不确定 TOP 1 是否应该在我放在这里的情况下放在案例之外,或者是否应该放在里面(其他 TOP 1 名称)。这个想法是:

SELECT TOP 1 CASE WHEN myexpression = 'true' THEN 'my message' ELSE name END
FROM people;

Here myexpression has to be either constants or related to the tables present in the query, for example

这里 myexpression 必须是常量或与查询中存在的表相关,例如

CASE WHEN address LIKE '%Michigan%'

where address is another field in the table people.

其中地址是表 people 中的另一个字段。

PS: Found the MSSQL CASE syntax here:-)

PS:在这里找到了 MSSQL CASE 语法:-)

回答by user35559

I just tried this on the AdventureWorks database and it works

我刚刚在 AdventureWorks 数据库上试过这个,它工作正常

Use AdventureWorks

Declare @myVar int
SET @myVar = 1

if (@myVar = 2)

     select top 2 * from HumanResources.Department

else

     select top 1 * from HumanResources.Department

回答by Bert

select top 1 name 
from people
where @MyParameter = whatever

union

select 'my message' as name
where @MyParameter != whatever

All in one statement.

全在一份声明中。