我正在使用SQL Server 2008 Enterprise。我在SQL Server Management Studio中使用以下语句作为存储过程的一部分,并且存在以下错误(当我按F5运行存储过程时编译错误)。但是当我删除count()时,所有错误都会消失。任何想法计数错误()?另一个问题是,我的目的是返回匹配结果的总数,只返回一部分结果来实现分页(在@startPos和@requireCount + @startPos-1之间使用tt.rowNum),任何想法如何实现?
SELECT *
FROM (SELECT count(*), t.id,t.AdditionalInfo, ROW_NUMBER()
OVER (order by t.id) AS rowNum
FROM dbo.foo t
CROSS APPLY t.AdditionalInfo.nodes('/AdditionalInfo')
AS MyTestXMLQuery(AdditionalInfo)
WHERE
(Tag4=''+@InputTag4+'' OR Tag5=''+@InputTag5+'')
and (MyTestXMLQuery.AdditionalInfo.value
('(Item[@Name="Tag1"]/@Value)[1]', 'varchar(50)')
LIKE '%'+@Query+'%'
or MyTestXMLQuery.AdditionalInfo.value
('(Item[@Name="Tag2"]/@Value)[1]', 'varchar(50)')
LIKE '%'+@Query+'%'
or MyTestXMLQuery.AdditionalInfo.value
('(Item[@Name="Tag3"]/@Value)[1]', 'varchar(50)')
LIKE '%'+@Query+'%') ) tt
WHERE tt.rowNum between @startPos and @requireCount + @startPos-1
错误讯息
Column 'dbo.foo.ID' is invalid in the select list
because it is not contained in either an aggregate function
or the GROUP BY clause.
No column name was specified for column 1 of 'tt'.
提前谢谢,
乔治
答案 0 :(得分:4)
将其替换为
SELECT count(*) over() AS [Count]
它需要别名,因为它是派生表中的列。
空over()
子句将返回整个派生表中的计数。这就是你需要的吗?
答案 1 :(得分:3)
如果没有GROUP BY
子句,通常无法混合聚合函数和正常字段选择。
在您只选择COUNT(*)
的查询中,它假设您要将所有内容整合在一个组中。一旦选择了另一个字段(没有相应的GROUP BY
),就会引入与该假设的矛盾,并且不会执行。
答案 2 :(得分:1)
您需要拥有GROUP BY子句。试试这个:
SELECT *
FROM (SELECT
count(*) AS c, t.id,t.AdditionalInfo
FROM
dbo.foo t
CROSS APPLY
t.AdditionalInfo.nodes('/AdditionalInfo') AS MyTestXMLQuery(AdditionalInfo)
WHERE
(Tag4=''+@InputTag4+'' OR Tag5=''+@InputTag5+'')
and (MyTestXMLQuery.AdditionalInfo.value('(Item[@Name="Tag1"]/@Value)[1]', 'varchar(50)') LIKE '%'+@Query+'%'
or MyTestXMLQuery.AdditionalInfo.value('(Item[@Name="Tag2"]/@Value)[1]', 'varchar(50)') LIKE '%'+@Query+'%'
or MyTestXMLQuery.AdditionalInfo.value('(Item[@Name="Tag3"]/@Value)[1]', 'varchar(50)') LIKE '%'+@Query+'%')
GROUP BY t.id,t.AdditionalInfo
) tt
WHERE tt.rowNum between @startPos and @requireCount + @startPos-1
可能会有更多。不确定。
无论哪种方式,关于关系数据库模型背后的理论,你都会有很多好处。此查询需要比我刚添加的更多帮助。我的意思是它需要更多的帮助。
编辑:您也不能在选择COUNT(*)的查询中使用ROW_NUMBER()。你会想要写什么?计数?
答案 3 :(得分:1)
猜测,因为我无法运行它,但请尝试将其更改为:
Select * From
(Select count(*), t.id, t.AdditionalInfo, ROW_NUMBER()
OVER (order by t.id) AS rowNum
From dbo.foo t
CROSS APPLY t.AdditionalInfo.nodes('/AdditionalInfo')
AS MyTestXMLQuery(AdditionalInfo)
Where
(Tag4=''+@InputTag4+'' OR Tag5=''+@InputTag5+'')
and (MyTestXMLQuery.AdditionalInfo.value
('(Item[@Name="Tag1"]/@Value)[1]', 'varchar(50)')
LIKE '%'+@Query+'%'
or MyTestXMLQuery.AdditionalInfo.value
('(Item[@Name="Tag2"]/@Value)[1]', 'varchar(50)')
LIKE '%'+@Query+'%'
or MyTestXMLQuery.AdditionalInfo.value
('(Item[@Name="Tag3"]/@Value)[1]', 'varchar(50)')
LIKE '%'+@Query+'%')
Group By t.id, t.AdditionalInfo ) tt
Where tt.rowNum between @startPos and @requireCount + @startPos-1