在查询中使用包含SQL的数据库字段

时间:2012-05-07 03:56:42

标签: sql sql-server sql-server-2008

我正在使用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

webcategories示例

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表返回的所有结果的帮助。非常感谢:)

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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')