Is it possible to use local table variables in a procedure inside an sql query contained in a VARCHAR variable?

浪尽此生 提交于 2019-12-11 09:36:03

问题


I have the following code:

DECLARE @temp_table_1 TABLE (id int identity(0, 1), col_1 varchar(50)), 
        @txtVar VARCHAR(MAX)

INSERT INTO @temp_table_1
  SELECT col_1 FROM table_1  -- This table_1 is a real table in the database.

Set @txtVar = 'SELECT * FROM @temp_table_1'

EXECUTE (@txtVar)

The error I get is

Declare variable @temp_table_1.

How can I fix this?


回答1:


Set @txtVar = 'SELECT * FROM myTable WHERE column_value=''' + @var1 + ''''

This article will help you get a basic ideas of dynamic sql.

EDIT
It is not possible to use table variables in a dynamic query.
You have to use temporary table or Use custom TABLE type.

Temporary table

 CREATE TABLE #temp_table_1 
  ( 
     id    INT IDENTITY(0, 1), 
     col_1 VARCHAR(50) 
  ) 

DECLARE @txtVar VARCHAR(MAX) 

INSERT INTO #temp_table_1 


SELECT col_1 
FROM   table_1 -- This table_1 is a real table in the database. 
SET @txtVar = 'SELECT * FROM  #temp_table_1' 

EXECUTE (@txtVar) 

DROP TABLE #temp_table_1 

Custom Table Type

CREATE TYPE DefaultTable AS TABLE (ID INT IDENTITY(0, 1), COL_1 VARCHAR(50))
GO

-- Fill a var of that type with some test data
DECLARE @MyTable DefaultTable
INSERT @MyTable 
SELECT col_1 FROM table_1 -- This table_1 is a real table in the database.

-- Now this is how you pass that var into dynamic statement
EXECUTE sp_executesql N'SELECT * FROM @MyTable', 
    N'@MyTable DefaultTable READONLY', 
    @MyTable


来源:https://stackoverflow.com/questions/9206251/is-it-possible-to-use-local-table-variables-in-a-procedure-inside-an-sql-query-c

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