从存储过程的OUTPUT参数运行查询

时间:2012-12-04 21:09:00

标签: sql sql-server tsql stored-procedures output-parameter

以下脚本旨在获取动态生成的SQL语句,然后运行它。该脚本将运行,但它不会返回预期的结果,而是返回动态SQL字符串的文本。产生的字符串是我需要运行的字符串,但它被调用了32次(奇怪的数字,我不知道为什么会这样)。有谁知道为什么这不只是返回动态生成的SQL语句的结果集? SQL Server 2008 R2

对于记录,SQL Server将查询解释为32个不同的select语句,每个语句都在各自的行中。

返回的字符串

SELECT DISTINCT x.patid 
FROM   (SELECT ic.patid 
        FROM   icdclm AS ic 
        WHERE  ic.icd LIKE '123%') AS x1 
       INNER JOIN (SELECT ic.patid 
                   FROM   icdclm AS ic 
                   WHERE  ic.icd LIKE '456%') x2 
               ON x2.patid = x1.patid 
       INNER JOIN (SELECT ic.patid 
                   FROM   icdclm AS ic 
                   WHERE  ic.icd LIKE '456%') x3 
               ON x3.patid = x1.patid 
       INNER JOIN (SELECT ic.patid 
                   FROM   icdclm AS ic 
                   WHERE  ic.icd LIKE '456%') x4 
               ON x4.patid = x1.patid 
       INNER JOIN (SELECT ic.patid 
                   FROM   icdclm AS ic 
                   WHERE  ic.icd LIKE '456%') x5 
               ON x5.patid = x1.patid 

我的代码产生上面的字符串而不是执行那个SQL:

ALTER PROC Getmultiplecomorbidquery (@sqlquery NVARCHAR(1000) output) 
AS 
    DECLARE @x   INT, 
            @y   INT, 
            @sql NVARCHAR(1000) 

    SELECT @x = 1, 
           @y = 5, 
           @sql = 'select distinct x.patid from ( select ic.patid from icdClm as ic where ic.icd like ''123%'' ) as  x' + Cast(@x AS CHAR(1)) 

    WHILE @x < @y 
      BEGIN; 
          SET @sql=@sql + '  inner join  ( select ic.patid from icdClm as ic where ic.icd like ''456%'' ) x' + Cast(@x+1 AS CHAR(1)) + ' on x' 
                   + Cast(@x+1 AS CHAR(1)) 
                   + '.patid=x1.patid' 
          SET @x=@x + 1 
      END; 

    SET @sqlquery = @sql 

    SELECT @sql 
code i used to call
    DECLARE @sqlquery NVARCHAR(1000) 

    SET @sqlquery='' 

    EXECUTE dbo.Getmultiplecomorbidquery 
      @sqlquery output 

    SELECT @sqlquery 

1 个答案:

答案 0 :(得分:0)

你永远不会执行查询,只需返回它,你需要一个     执行@sql 在那里(或执行结果)。