以下脚本旨在获取动态生成的 SQL 语句,然后运行它。该脚本将运行,但它不会返回预期的结果,而是返回动态 SQL 字符串的文本。产生的字符串是我需要运行的字符串,但它被调用了32次(奇怪的数字,我不知道为什么会这样)。有谁明白为什么这不仅仅是返回动态生成的 SQL 语句的结果集?SQL Server 2008 R2
作为记录,SQL Server 将查询解释为 32 条不同的选择语句,每条语句都在自己的行中。
返回的字符串
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