如何在SQL Server 2012中运行子查询?

时间:2012-12-22 19:21:03

标签: sql sql-server-2012

SELECT [SKULL].[dbo].[reports].[idnumber], [SKULL].[dbo].[reports].[subid] 
FROM [SKULL].[dbo].[reports] 
WHERE reportColumn =  (SELECT DISTINCT(reportColumn)
                       FROM [SKULL].[dbo].[reports] 
                       WHERE [SKULL].[dbo].reports.reportColumn 
                       LIKE '%someword%')

我收到一条错误消息

Msg 512, Level 16, State 1, Line 2
Subquery returned more than 1 value. 
This is not permitted when the subquery follows =, !=, <, <= , >, >= or 
when the subquery is used as an expression.

感谢。

5 个答案:

答案 0 :(得分:2)

我不太确定你在这里要做什么。如果我们假设您要返回所有报表记录,其中报表列与所有包含相同单词的报表列的不同列表匹配,那么您的工作量太大了。你可以这样写:

SELECT [SKULL].[dbo].[reports].[idnumber], [SKULL].[dbo].[reports].[subid] 
FROM [SKULL].[dbo].[reports] 
WHERE reportColumn LIKE '%someword%';

如果这不是您想要的,请检查您的查询,尤其是列名和表名。如果在这种情况下仍然无法弄清楚如何编写查询,请发布一些示例值和预期结果。

答案 1 :(得分:1)

如果子查询返回多行,则使用IN而不是=作为

SELECT [SKULL].[dbo].[reports].[idnumber], [SKULL].[dbo].[reports].[subid] 
FROM [SKULL].[dbo].[reports] 
WHERE reportColumn IN  (SELECT DISTINCT(reportColumn)
                       FROM [SKULL].[dbo].[reports] 
                       WHERE [SKULL].[dbo].reports.reportColumn 
                       LIKE '%someword%')

OR

如果你确定子查询返回单行然后用作

SELECT [SKULL].[dbo].[reports].[idnumber], [SKULL].[dbo].[reports].[subid] 
FROM [SKULL].[dbo].[reports] 
WHERE reportColumn =  (SELECT top(1) DISTINCT(reportColumn)
                       FROM [SKULL].[dbo].[reports] 
                       WHERE [SKULL].[dbo].reports.reportColumn 
                       LIKE '%someword%' order by idnumber)

答案 2 :(得分:0)

您正在执行where field=subquery,这是一个相等测试 - 子查询MUSt返回 SINGLE 值,例如1行,值为1。现在2行,而不是2个字段。如果您要返回多行,则必须为where field IN (subquery)

答案 3 :(得分:0)

如错误所述,您的子查询只能返回单个记录。尝试使用TOP 1执行此操作。

SELECT [SKULL].[dbo].[reports].[idnumber],  [SKULL].[dbo].[reports].[subid] FROM [SKULL].[dbo].[reports] WHERE reportColumn =  (SELECT TOP 1 reportColumn
  FROM [SKULL].[dbo].[reports] WHERE [SKULL].[dbo].reports.reportColumn LIKE '%someword%')

答案 4 :(得分:0)

错误原因:尝试将单个值与多个值进行比较。

解决方案:限制内部查询返回1值或更改where条件以与多个返回集进行比较。

与单个值比较: SELECT [SKULL]。[dbo]。[reports]。[idnumber],[SKULL]。[dbo]。[reports]。[subid] FROM [SKULL]。[dbo]。[reports] WHERE reportColumn =(SELECT TOP1 reportColumn FROM [SKULL]。[dbo]。[reports] WHERE [SKULL]。[dbo] .reports.reportColumn LIKE'%someword%')

OR

与多个返回集相比

SELECT [SKULL]。[dbo]。[reports]。[idnumber],[SKULL]。[dbo]。[reports]。[subid] FROM [SKULL]。[dbo]。[reports] WHERE reportColumn in (SELECT DISTINCT(reportColumn) FROM [SKULL]。[dbo]。[reports] WHERE [SKULL]。[dbo] .reports.reportColumn LIKE'%someword%')