0

对于我正在使用 SQL Server 处理的查询,我需要一些帮助。

该查询获取特定类别的搜索字段信息,并使用它返回按该类别中的配置文件数量排序的配置文件列表。

我需要使用 wn.sqlcheck 字段中包含的信息运行查询。然后按sectionCount 排序。

查询

SELECT wc.name,
   (SELECT count(*) FROM facilities WHERE wc.sqlcheck) AS sectionCount
FROM webcategories wc
WHERE wc.parentid = 1
ORDER BY sectionCount

网络类别示例

parentid | name           | sqlcheck 
-----------------------------------------
1        | categorytitle  | (highcaretotalnumberbeds > 0 AND highcaredoubleroomsyn = 1)
1        | categorytitle2 | (othernumberbeds > 0 AND otherdoubleroomsyn = 1)

我现在正在使用存储过程

SET @sqlcheck = (select sqlcheck from webcategories where parentid=1)

EXEC('SELECT wc.id, wc.name,
   (SELECT count(id) FROM facilities WHERE '+@sqlcheck+') AS sectionCount
FROM webcategories wc
WHERE wc.parentid = 1
ORDER BY sectionCount')

发生此错误:

子查询返回超过 1 个值。当子查询跟随 =、!=、<、<=、>、>= 或子查询用作表达式时,这是不允许的。

这是因为 parentid = 1 的子查询返回了多行。

我仍然需要有关如何遍历从 webcategories 表返回的所有结果的帮助。非常感激 :)

4

2 回答 2

1

你可以这样尝试

  declare  @name  varchar(100)
    set @name=(select name from webcategories where parentid=1 )
    declare  @sqlcheck  varchar(100)
    set @sqlcheck=(select sqlcheck from webcategories where parentid=1 )

    exec('SELECT wc.'+@name+',
       (SELECT count(*) FROM facilities WHERE '+@sqlcheck+') AS sectionCount
    FROM webcategories wc
    WHERE wc.parentid = 1
    ORDER BY sectionCount')
于 2012-05-07T06:39:49.883 回答
1

实际上,您需要使用sp_executesql。详细示例可以在这里找到:http: //msdn.microsoft.com/en-us/library/ms188001 (v=sql.100).aspx 。

以下是如何使用游标循环(它的快速版本):

DECLARE @catName varchar(100), @sqlCheck varchar(max)

DECLARE webcat_cursor CURSOR FAST_FORWARD READ_ONLY FOR 
SELECT name, sqlcheck
FROM webcategories
WHERE parentId = 1
ORDER BY sectionCount

OPEN webcat_cursor

FETCH NEXT FROM webcat_cursor
INTO @catName, @sqlCheck

WHILE @@FETCH_STATUS = 0
BEGIN
    --the query to be executed
    --I have taken it from one of the answers
    EXEC('SELECT wc.' + @catName + ',
       (SELECT count(*) FROM facilities WHERE ' + @sqlCheck + ') AS sectionCount    
    FROM webcategories wc
    WHERE wc.parentid = 1
    ORDER BY sectionCount')
    --end of executed query

    FETCH NEXT FROM webcat_cursor 
    INTO @catName, @sqlCheck
END

CLOSE webcat_cursor
DEALLOCATE webcat_cursor
于 2012-05-07T05:20:20.440 回答