存储过程动态 SQL 将结果存储在变量中
我在上面写了一个存储过程
DECLARE @AreaID AS INT
DECLARE @DayPrior AS INT
DECLARE @TableName AS VARCHAR(50)
DECLARE @StoreQuery AS NVARCHAR(MAX)
DECLARE @SQL_ExtractDlSql AS NVARCHAR(MAX)
DECLARE @ParameterDefinition AS NVARCHAR(2000)
SET @AreaID = 1
SET @DayPrior = 1
SET @TableName = 'Tbl_Lube'
SET @SQL_ExtractDlSql = 'SELECT Download_SQL From
HDDDataPackage.dbo.tbl_HDD_DataDownloadSetting
Where AreaId=@AreaID AND TableName=@TableName'
SET @ParameterDefinition = '@AreaID INT,@DayPrior INT,@TableName VARCHAR(50)'
EXECUTE sp_executesql @SQL_ExtractDlSql,
@ParameterDefinition,
@AreaID,
@DayPrior,
@TableName
PRINT @SQL_ExtractDlSql
存储过程,我得到了我想要的打印结果,但我没有这样做,而是希望将选定的数据存储作为变量。 然后我所做的是声明一个变量@StoreSql,并对 SQL 语句进行一些修改,如下所示:
变量声明:
DECLARE @StoreSql AS NVARCHAR(MAX)
修改代码:
SET @SQL_ExtractDlSql = 'SELECT @StoreSql = Download_SQL From
HDDDataPackage.dbo.tbl_HDD_DataDownloadSetting
Where AreaId=@AreaID AND TableName=@TableName'
我执行代码,出现错误必须声明标量变量“@StoreSql”。
我完全不知道如何处理这个问题。任何人都可以提供帮助。此外,我是 sqlserver 的新手,也是存储过程的新手。
请毫不犹豫地指出我的任何错误,任何错误……例如逻辑或等等。我从错误中学习。
问候 梁克
I have A stored procedure written
DECLARE @AreaID AS INT
DECLARE @DayPrior AS INT
DECLARE @TableName AS VARCHAR(50)
DECLARE @StoreQuery AS NVARCHAR(MAX)
DECLARE @SQL_ExtractDlSql AS NVARCHAR(MAX)
DECLARE @ParameterDefinition AS NVARCHAR(2000)
SET @AreaID = 1
SET @DayPrior = 1
SET @TableName = 'Tbl_Lube'
SET @SQL_ExtractDlSql = 'SELECT Download_SQL From
HDDDataPackage.dbo.tbl_HDD_DataDownloadSetting
Where AreaId=@AreaID AND TableName=@TableName'
SET @ParameterDefinition = '@AreaID INT,@DayPrior INT,@TableName VARCHAR(50)'
EXECUTE sp_executesql @SQL_ExtractDlSql,
@ParameterDefinition,
@AreaID,
@DayPrior,
@TableName
PRINT @SQL_ExtractDlSql
I above Stored procedure, I get What I wanted on print, but instead of doing that, I wanted the selected data stores as a variable.
Then what I done is I declared a variable @StoreSql and made some modified into the SQL statement show below:
Variable Declaration:
DECLARE @StoreSql AS NVARCHAR(MAX)
Modified the Code:
SET @SQL_ExtractDlSql = 'SELECT @StoreSql = Download_SQL From
HDDDataPackage.dbo.tbl_HDD_DataDownloadSetting
Where AreaId=@AreaID AND TableName=@TableName'
I executed the code, I get error Must declare the scalar variable "@StoreSql".
I have totally no idea how to deal with this.Any one can help.Beside,I am new to sqlserver,new to stored procedures.
Please don't hesitate to point out my any mistake,any..such as logic or etc. I learn from mistake.
Regards
LiangCk
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
动态 SQL 字符串无法引用外部作用域中的变量。您需要将其声明为
output
参数The dynamic SQL string cannot reference variables from the outer scope. You need to declare it as an
output
parameter