我有以下代码:
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)
我得到的错误是
声明变量@ temp_table_1。
我该如何解决这个问题?
答案 0 :(得分:4)
Set @txtVar = 'SELECT * FROM myTable WHERE column_value=''' + @var1 + ''''
This文章将帮助您了解动态SQL的基本概念。
修改强>
在动态查询中无法使用表变量
您必须使用临时表或Use custom TABLE type。
临时表
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
自定义表格类型
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