如何从 sql 语句返回常量?

发布于 2024-07-08 12:06:52 字数 202 浏览 9 评论 0原文

如何从 sql 语句返回常量?

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

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

我正在使用 ms sql 2000

How do I return a constant from an sql statement?

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

猫七 2024-07-15 12:06:52

你试过了吗:

select 'my message';

Did you try:

select 'my message';
§对你不离不弃 2024-07-15 12:06:52
select "my message" as message
select "my message" as message
奶气 2024-07-15 12:06:52

我没有方便的 MSSQL,但请检查 CASE 语句的语法,以防万一我弄错了,而且我不确定 TOP 1 是否应该像我放在此处的那样放在 case 之外,或者是否应该放在里面(其他前 1 位名称)。 这个想法是:

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

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

CASE WHEN address LIKE '%Michigan%'

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

PS:在此处找到了 MSSQL CASE 语法 :-)

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:

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

CASE WHEN address LIKE '%Michigan%'

where address is another field in the table people.

PS: Found the MSSQL CASE syntax here :-)

开始看清了 2024-07-15 12:06:52
select top 1 name 
from people
where @MyParameter = whatever

union

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

一切尽在一份声明中。

select top 1 name 
from people
where @MyParameter = whatever

union

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

All in one statement.

深海蓝天 2024-07-15 12:06:52

我刚刚在 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

I just tried this on the AdventureWorks database and it works

Use AdventureWorks

Declare @myVar int
SET @myVar = 1

if (@myVar = 2)

     select top 2 * from HumanResources.Department

else

     select top 1 * from HumanResources.Department
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文