Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 将where子句作为存储过程参数传递时出错_Sql_Sql Server - Fatal编程技术网

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

Sql 将where子句作为存储过程参数传递时出错,sql,sql-server,Sql,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;

我在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
我试着这样称呼它

exec sp_test 'title,name','person','where name = ''john'''
我遇到了这样的错误

味精102,第15级,状态1,第1行
“=”附近的语法不正确


您有一个额外的单引号,为什么不使用双引号,如:

exec sp_test 'title,name','person'," where name = 'john'"
在此处添加额外的空间:

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

提示:这是因为

SELECT title,name FROM personwhere name = 'john'
不是有效的SQL


原因现在应该是显而易见的,留给读者作为练习…

旁注:您不应该在存储过程中使用
sp\ucode>前缀。微软已经这样做了,而且你确实有可能在将来的某个时候发生名称冲突。最好只是简单地避免使用
sp.
并使用其他东西作为前缀,或者根本不使用前缀!谢谢@marc_,我会换的。