Is it possible to pass a table name into a stored proc and use it without the Exec Function?

我与影子孤独终老i 提交于 2020-01-04 14:06:01

问题


I would like to create a SP or UDF where I supply a table and column name as a parameter and it does something to that target. I'm using Sql Server 2005

Trivial Example of what I'm trying to accomplish:

CREATE FUNCTION Example (@TableName AS VARCHAR(100))
RETURNS TABLE
AS
BEGIN
    SELECT * 
    INTO #temp
    FROM @TableName

    RETURN #temp
END

The example is just something trivial to illustrate what I'm trying to accomplish in terms of passing the Table name as a parameter.

Is this possible to do w/o concatinating strings and calling the EXEC function?

Ultimately, I'm trying to convert the answer from this question into something reusable.


回答1:


This reeks of SQL injection. You would still need to use EXEC to do this.




回答2:


No. Can't do it. Sadly, there is no macro pre-complier in T-SQL. The closest you'll get is SQLCMD mode, but that's only for scripts, can't use it in object definitions.

Are you doing the same thing to the table each time?

You could dynamically redefine a synonym, but that still requires an EXEC and you lose concurrency. You could serialize execution with a queue, but at that point you may be better off w/ plain old dynamic SQL.

You might try temporary tables, not passed in as a variable, but created in the parent connection or calling procedure. eg.

create proc #proc as
select * from #table
go

create table #table (col1 int)
insert #table values (1)
insert #table values (2)
insert #table values (3)
go

exec #proc
go

For more ways to share data between stored procedures, see here: http://www.sommarskog.se/share_data.html



来源:https://stackoverflow.com/questions/1607918/is-it-possible-to-pass-a-table-name-into-a-stored-proc-and-use-it-without-the-ex

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!