如何合并这两个 Select 语句?

发布于 2024-12-17 22:34:00 字数 219 浏览 0 评论 0原文

如何合并这 2 个 select 语句以便返回 3 列?

第一个选择仅返回文本值,而第二个选择返回表列值。如果第二个表没有返回值,第一个选择仍然应该有值并且名称列可以为空

SELECT 'column1', 'column2'

SELECT Name
FROM [dbo].[TableName]
WHERE ID = @id

非常感谢,

How to merge these 2 select statements so that 3 columns are returned?

the first select only returns text values whereas the second select returns a table column value. If the second table returns no value, still the first select should have value and the name column can be null

SELECT 'column1', 'column2'

SELECT Name
FROM [dbo].[TableName]
WHERE ID = @id

Many thanks,

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

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

发布评论

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

评论(4

〃温暖了心ぐ 2024-12-24 22:34:00

您的意思是这样的吗:

SELECT 'column1', 'column2', Name
FROM [dbo].[TableName]
WHERE ID = @id

这将为表中具有匹配 ID 的每一行返回一行。


更新:

此查询将完全按照您的要求执行:

IF (SELECT COUNT(Name) FROM [dbo].[TableName] WHERE ID = @id) = 0
BEGIN
 SELECT 'column1', 'column2', NULL
END
ELSE
BEGIN
    SELECT 'column1', 'column2', Name
    FROM [dbo].[TableName]
    WHERE ID = @id
END

Do you mean something like this:

SELECT 'column1', 'column2', Name
FROM [dbo].[TableName]
WHERE ID = @id

This will return a row for each row with a matching ID in the table.


Update:

This query will do exactly what you want:

IF (SELECT COUNT(Name) FROM [dbo].[TableName] WHERE ID = @id) = 0
BEGIN
 SELECT 'column1', 'column2', NULL
END
ELSE
BEGIN
    SELECT 'column1', 'column2', Name
    FROM [dbo].[TableName]
    WHERE ID = @id
END
烟燃烟灭 2024-12-24 22:34:00

这会更简单,不需要重复固定列:

DECLARE @name nvarchar(255)

SELECT @name=Name FROM [dbo].[TableName] WHERE ID = @id 

SELECT 'column1', 'column2', @name AS 'Name'

this would be simpler, no need to duplicate the fixed columns:

DECLARE @name nvarchar(255)

SELECT @name=Name FROM [dbo].[TableName] WHERE ID = @id 

SELECT 'column1', 'column2', @name AS 'Name'
梦在深巷 2024-12-24 22:34:00

您可以有一个这样的查询:

SELECT
  'column1',
  'column2',
  (
    SELECT Name
    FROM [dbo].[TableName]
    WHERE ID = @id
  ) AS 'Name'

You can have one query like this:

SELECT
  'column1',
  'column2',
  (
    SELECT Name
    FROM [dbo].[TableName]
    WHERE ID = @id
  ) AS 'Name'
苦笑流年记忆 2024-12-24 22:34:00

如果(看起来很可能)最多只能进行一场比赛,那么安德烈或威廉的解决方案是最好的。如果由于某种奇怪的原因 Id 不是主键,那么以下内容将执行您想要的操作。

SELECT a.column1, a.column2, t.Name
  FROM 
  (
    SELECT 'column1' AS column1, 'column2' AS column2
  ) a
  LEFT JOIN [dbo].[TableName] t ON (t.ID = @Id)

我感觉有点脏……

If, as seems likely, there can only be at most one match then Andriy or William's solutions are the best. If for some strange reason Id isn't a primary key then the following will do what you want.

SELECT a.column1, a.column2, t.Name
  FROM 
  (
    SELECT 'column1' AS column1, 'column2' AS column2
  ) a
  LEFT JOIN [dbo].[TableName] t ON (t.ID = @Id)

I feel kinda dirty....

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