如何在SQL函数中使用动态表名称 [英] How do I use dynamic table name in SQL function
本文介绍了如何在SQL函数中使用动态表名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个sql存储过程而不是runnig并行。
进程写入包含会话ID的临时表在最后
,这样每个进程都有自己的临时表。
例子
Hi,
I have a sql store procedure than runnig in parallel.
The process write to temp table that contain session id in the last
so that each process has its own temp table.
example
##temp_table + CONVERT(varchar(10),(select @@SPID))
创建的表格
The tables that created
##temp_table_121
##temp_table_122
问题
我需要在功能中从这些表中选择数据。
但是在功能上我不能使用动态sql。
如何在功能中使用这些表?
我尝试过:
在函数中使用动态sql - 我生成错误
The problem
I need to select data from these tables in function.
But in function I can't use dynamic sql.
How can I use these tables in function?
What I have tried:
Using dynamic sql in function - I gen an error
推荐答案
根据我的想法,你需要使用exec sp_executesql。这是一个例子。
Based on what i think you are trying to do, you need to use exec sp_executesql. Here is an example.
IF OBJECT_ID('tempdb..#MyTempTable') IS NOT NULL DROP TABLE #MyTempTable
CREATE TABLE #MyTempTable
(
Id INT NULL
)
DECLARE @TableName VARCHAR(200) = '#MyTempTable';
DECLARE @Sql NVARCHAR(500) = 'SELECT * FROM ' + @TableName;
EXEC sp_executesql @Sql
我的解决方案:
我创建了一个SQL表类型。
在商店程序中运行我声明的函数这种类型的对象,将临时表数据插入此对象并将其传递给函数。
My solution:
I have created a SQL table type.
In the store procedure than run the function I have declared an object of this type, insert the temp table data to this object and passed it to the function.
这篇关于如何在SQL函数中使用动态表名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文