Stored procedures 如何使用Like cluse in store过程从表中获取数据?
这里我想从表中获取一些结果,因为我有如下所示的writer SpStored procedures 如何使用Like cluse in store过程从表中获取数据?,stored-procedures,sql-server-2012,Stored Procedures,Sql Server 2012,这里我想从表中获取一些结果,因为我有如下所示的writer Sp create proc GetData ( @tableName nvarchar(max), @groupLetter nvarchar(max) ) as begin EXEC('Select * from ' + @tablename + 'where LastName LIKE'''+'%'+@groupLetter+'%'+'''ORDER BY LastName') end 我向该SP传递表名和文本以查找结
create proc GetData
(
@tableName nvarchar(max),
@groupLetter nvarchar(max)
)
as
begin
EXEC('Select * from ' + @tablename + 'where LastName LIKE'''+'%'+@groupLetter+'%'+'''ORDER BY LastName')
end
我向该SP传递表名和文本以查找结果。
此操作成功创建SP,但在执行时出错
这就是我执行SP的方式。
执行官GetData员工,ab
我得到的错误如下。
关键字“LIKE”附近的语法不正确。您的代码应该如下所示:
declare @sql nvarchar(max) = N'Select * from ' + @tablename + N' where LastName LIKE '''+N'%'+@groupLetter+N'%'+N''' ORDER BY LastName'
EXEC(@sql);
您遇到的第一个错误是在查询的关键字之间缺少一些空格,第二个错误:
exec
不接受字符串连接,因此您应该在变量中构造查询,然后将其传递到exec
您的代码应该如下所示:
declare @sql nvarchar(max) = N'Select * from ' + @tablename + N' where LastName LIKE '''+N'%'+@groupLetter+N'%'+N''' ORDER BY LastName'
EXEC(@sql);
您遇到的第一个错误是在查询的关键字之间缺少一些空格,第二个错误:
exec
不接受字符串连接,因此您应该在变量中构造查询,然后将其传递到exec
这只是字符串中的语法错误(没有足够的空格)。应该是:
begin
EXEC('Select * from ' + @tablename + ' where LastName LIKE '''+'%'+@groupLetter+'%'+''' ORDER BY LastName')
end
这只是字符串中的语法错误(没有足够的空格)。应该是:
begin
EXEC('Select * from ' + @tablename + ' where LastName LIKE '''+'%'+@groupLetter+'%'+''' ORDER BY LastName')
end
是的,我很接近。Thanxyep,我非常接近。塔克斯