参数被视为列名,而不是使用动态SQL的列值

时间:2021-12-31 20:11:34

This is my first time here and I want to ask a question.

这是我第一次来这里,我想问一个问题。

Here is my stored procedure...

这是我的存储过程......

ALTER procedure [dbo].[GetDataFromTable]
@tablename sysname,
@DocumentName nvarchar(50),
@Uploader nvarchar(50)

as
begin

if @tablename = 'Document_Data'
EXEC('Select * from Document_Data where DocumentName = ('+ @DocumentName +') and Uploader = ('+ @Uploader +')')

end

and the problem is... the stored procedure reads the DocumentName and Uploader parameters as column names, not the values themselves. I already tried to use aliases and other things that I scoured from the Internet, but they don't work.

问题是......存储过程将DocumentName和Uploader参数作为列名读取,而不是值本身。我已经尝试使用别名和我从互联网上搜索的其他东西,但它们不起作用。

What could be the problem behind this? Oh, and BTW I am a newbie to Dynamic SQL. Thanks.

这可能是什么问题?哦,BTW我是Dynamic SQL的新手。谢谢。

1 个解决方案

#1


1  

You should add '' chars to dynamic sql after and before your parameters as below:

您应该在参数之前和之后向动态sql添加''字符,如下所示:

ALTER procedure [dbo].[GetDataFromTable]
@tablename sysname,
@DocumentName nvarchar(50),
@Uploader nvarchar(50)

as
begin

if @tablename = 'Document_Data'
EXEC('Select * from Document_Data where DocumentName = ('''+ @DocumentName +''') and Uploader = ('''+ @Uploader +''')')

end

#1


1  

You should add '' chars to dynamic sql after and before your parameters as below:

您应该在参数之前和之后向动态sql添加''字符,如下所示:

ALTER procedure [dbo].[GetDataFromTable]
@tablename sysname,
@DocumentName nvarchar(50),
@Uploader nvarchar(50)

as
begin

if @tablename = 'Document_Data'
EXEC('Select * from Document_Data where DocumentName = ('''+ @DocumentName +''') and Uploader = ('''+ @Uploader +''')')

end