gpt4 book ai didi

sql - 将表变量与 sp_executesql 一起使用

转载 作者:行者123 更新时间:2023-12-01 21:59:43 25 4
gpt4 key购买 nike

我有一个包含表变量的查询:

DECLARE @Selects    XML ;
SET @Selects='<Selects><Select><Q_ID>1</Q_ID><Q_DESC>nima1</Q_DESC></Select><Select><Q_ID>2</Q_ID><Q_DESC>nima2</Q_DESC></Select><Select><Q_ID>3</Q_ID><Q_DESC>nima3</Q_DESC></Select></Selects>'

DECLARE @QuestionID NVARCHAR(10);
SET @QuestionID='a5';

DECLARE @TblSelect TABLE
(
Q_ID INT,
Q_DESC NVARCHAR(500)
)

INSERT INTO @TblSelect
(
Q_ID,Q_DESC
)
SELECT Q_Select.value('(Q_ID)[1]', 'int') AS 'Q_ID',
Q_Select.value('(Q_DESC)[1]', 'nvarchar(500)') AS 'Q_DESC'
FROM @Selects.nodes('/Selects/Select') AS AllSelects(Q_Select)

DECLARE @Query NVARCHAR(4000);
SET @Query=N'SELECT Q_ID,COUNT(Q_ID) FROM @TblSelect LEFT OUTER JOIN tblbase tb ON @TblSelect.Q_ID = @Col_Select group by Q_ID';

EXECUTE sp_executesql @Query,@TblSelect,@Col_Select

如何将表变量传递给我的查询?

最佳答案

下面是如何将表值参数传递给 sp_executesql 的示例。该变量必须传递readonly:

if exists (select * from sys.types where name = 'TestTableType')
drop type TestTableType

create type TestTableType as table (id int)
go
declare @t TestTableType
insert @t select 6*7

exec sp_executesql N'select * from @var', N'@var TestTableType readonly', @t

这将打印 Answer to the Ultimate Question of Life, the Universe, and Everything .

关于sql - 将表变量与 sp_executesql 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7329996/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com