我正在构建一个使用基本动态SQL的过程。我想在所述过程的另一部分中使用动态SQL(@query)的结果。下面是我试图完成的代码的简写版本。
不使用sp_executesql ,如何将@query的结果值传递到IF块?
DECLARE @table VARCHAR(MAX)
DECLARE @query VARCHAR(MAX)
DECLARE @map VARCHAR(MAX)
SET @table = 'SomeTable'
SET @query = '
;WITH Assignment AS
(
SELECT
''' + @table + ''' AS src
,Type
,RANK () OVER(ORDER BY COUNT(type) as rnk
FROM ' + @table + '
GROUP BY Type
)
SELECT Type
FROM Assignment
WHERE rnk = ''1'''
IF (@query = 'typeA')
BEGIN
/* preform an upsert dynamically */
END
IF (@query = 'typeB')
BEGIN
/* preform a delete dynamically */
END
IF (@query = 'typeC')
BEGIN
/* preform an alter dynamically */
END
答案 0 :(得分:2)
为什么在用一些SQL设置后立即测试@query?
你可以使用临时表:
Create Table #temp(type...)
SET @query = '
;WITH Assignment AS
(
SELECT
''' + @table + ''' AS src
,Type
,RANK () OVER(ORDER BY COUNT(type) as rnk
FROM ' + @table + '
GROUP BY Type
)
Insert Into #temp(type)
SELECT Type
FROM Assignment
WHERE rnk = ''1'''
您也可以在if语句中构建动态查询,但我不确定它是否适用于您的情况:
SET @q1 = '
;WITH Assignment AS
(
SELECT
''' + @table + ''' AS src
,Type
,RANK () OVER(ORDER BY COUNT(type) as rnk
FROM ' + @table + '
GROUP BY Type
)'
set @q2 = 'SELECT Type
FROM Assignment
WHERE rnk = ''1'''
Case When @type = 'A' then @query = @q1 + 'Insert into... ' + @q2
Case When @type = 'B' then @query = @q1 + 'Update... ' + @q2
Case When @type = 'B' then @query = @q1 + 'delete from where type in (' + @q2 + ')' end
如果您改变主意,使用 sp_executesql 也很容易:
create table #temp(type int)
insert into #temp
exec sp_executesql @query
或者如果没有数千行:
declare @temp table(type int)
insert into @temp
exec sp_executesql @query
如果只有一行,仍然使用 sp_executesql 和一个参数,这是最佳选择:
declare @type varchar(10)
SET @query = '
declare @type varchar(10)
;WITH Assignment AS
(
SELECT
''' + @table + ''' AS src
,Type
,RANK () OVER(ORDER BY COUNT(type) as rnk
FROM ' + @table + '
GROUP BY Type
)
SELECT @type = Type
FROM Assignment
WHERE rnk = ''1''';
exec sp_executesql @query, N'@type varchar(10)', @type = @type