简体   繁体   English

将where子句作为存储过程参数传递时出错

[英]Error while passing a where clause as a stored procedure parameter

I have created following stored procedure in SQL Server, 我在SQL Server中创建了以下存储过程,

create procedure sp_test
    @columns nvarchar(max),
    @tablename nvarchar(max),
    @whereClause nvarchar(max)
as
   DECLARE @sql AS NVARCHAR(MAX)
   SET @sql = 'SELECT ' + @columns + ' FROM ' + @tablename + @whereClause;

   EXEC sp_executesql @sql

I am trying to call it like this 我试着这样称呼它

exec sp_test 'title,name','person','where name = ''john'''

And I'm getting an error like this, 我收到这样的错误,

Msg 102, Level 15, State 1, Line 1 Msg 102,Level 15,State 1,Line 1
Incorrect syntax near '='. '='附近的语法不正确。

You have an extra single quote, why not use double quote, like: 你有一个额外的单引号,为什么不使用双引号,如:

exec sp_test 'title,name','person'," where name = 'john'"

Add an extra space also here: 在这里添加一个额外的空间:

SET @sql = 'SELECT ' + @columns + ' FROM ' + @tablename+ ' ' + @whereClause;

Hint: It's because 提示:这是因为

SELECT title,name FROM personwhere name = 'john'

is not a valid SQL. 不是有效的SQL。

The reason should be obvious now and is left as an exercise to the reader... 原因应该是现在显而易见的,并留给读者练习......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM