sql server存储过程单引号

时间:2012-07-27 06:01:29

标签: sql-server-2005 stored-procedures

我对这个程序感到很困惑。请用引号纠正我的错误。

create procedure queryingsfor 
  @Tabname nvarchar(250),
  @colname nvarchar(250),
  @opname nvarchar(290),
  @valuesname nvarchar(239) 
as
begin
  set NOCOUNT on;
  declare @sql varchar(4000)
  set @sql='select * from' +@Tabname+ 'where' +@colname+''''+@opname+''''+ ''''+@valuesname+''''
  exec(@sql)
end
exec queryingsfor 'education','eduCurrentStudy','=','DME'

我只是得到了:

  

错误:消息102,级别15,状态1,行1   'fromeducationwhereeduCurrentStudy'附近的语法不正确。

2 个答案:

答案 0 :(得分:3)

你可能想在那里添加一些空格

set @sql='select * from ' +@Tabname+ ' where ' 
           +@colname+''''+@opname+''''+ ''''+@valuesname+'''' 

正确的陈述类似于

set @sql='select * from ' +@Tabname+ ' where '
           +@colname + @opname+ ''''+@valuesname+'''' 

更好

set @sql='select * from [' +@Tabname+ '] where 
           [' +@colname + ']' + @opname+ ''''+@valuesname+''''

答案 1 :(得分:1)

为了保护您免受SQL injection的攻击,您应该这样做。

alter procedure queryingsfor 
  @Tabname nvarchar(250),
  @colname nvarchar(250),
  @opname nvarchar(4),
  @valuesname nvarchar(239) 
as
begin
  set NOCOUNT on;
  declare @sql nvarchar(4000)
  set @sql = 'select * from '+quotename(@Tabname)+ ' where ' +quotename(@colname)+@opname+'@valuesname'
  exec sp_executesql @sql, N'@valuesname nvarchar(239)', @valuesname
end