当前位置: 数据库>sqlserver
mssql存储过程表名和字段名为变量的实现方法
来源: 互联网 发布时间:2014-10-04
本文导语: 没有使用动态语句直接报错 错误的 代码如下: alter proc testpapers as begin declare @tems nvarchar(max),@zidaun nvarchar(max) set @tems=select * from @tems order by @zidaun exec(@tems) end exec testpapers 消息 156,级别 15,状态 1,过程 testpapers,第 1 行 关键...
没有使用动态语句直接报错
错误的
alter proc testpapers
as
begin
declare @tems nvarchar(max),@zidaun nvarchar(max)
set @tems=select * from @tems order by @zidaun
exec(@tems)
end
exec testpapers
消息 156,级别 15,状态 1,过程 testpapers,第 1 行
关键字 'select' 附近有语法错误。
消息 1087,级别 15,状态 2,过程 testpapers,第 1 行
必须声明表变量 "@tems"。
首先要让表名或者字段为变量则要用到动态语句
错误的
alter proc testpapers
as
begin
declare @tems nvarchar(max),@zidaun nvarchar(max)
set @tems='select * from @tems order by @zidaun ';
exec(@tems)
end
exec testpapers
消息 1087,级别 15,状态 2,第 1 行
必须声明表变量 "@tems"。
将表名和字段名写到exec里边
正确的
alter proc testpapers
as
begin
declare @startRow nvarchar(max),@tems nvarchar(max),@zidaun nvarchar(max)
set @startRow='temp'
set @tems='select * from ';
set @zidaun='p_id';
exec(@tems+@startRow+' order by '+@zidaun)
end
exec testpapers
错误的
代码如下:
alter proc testpapers
as
begin
declare @tems nvarchar(max),@zidaun nvarchar(max)
set @tems=select * from @tems order by @zidaun
exec(@tems)
end
exec testpapers
消息 156,级别 15,状态 1,过程 testpapers,第 1 行
关键字 'select' 附近有语法错误。
消息 1087,级别 15,状态 2,过程 testpapers,第 1 行
必须声明表变量 "@tems"。
首先要让表名或者字段为变量则要用到动态语句
错误的
代码如下:
alter proc testpapers
as
begin
declare @tems nvarchar(max),@zidaun nvarchar(max)
set @tems='select * from @tems order by @zidaun ';
exec(@tems)
end
exec testpapers
消息 1087,级别 15,状态 2,第 1 行
必须声明表变量 "@tems"。
将表名和字段名写到exec里边
正确的
代码如下:
alter proc testpapers
as
begin
declare @startRow nvarchar(max),@tems nvarchar(max),@zidaun nvarchar(max)
set @startRow='temp'
set @tems='select * from ';
set @zidaun='p_id';
exec(@tems+@startRow+' order by '+@zidaun)
end
exec testpapers
您可能感兴趣的文章:
本站(WWW.)旨在分享和传播互联网科技相关的资讯和技术,将尽最大努力为读者提供更好的信息聚合和浏览方式。
本站(WWW.)站内文章除注明原创外,均为转载、整理或搜集自网络。欢迎任何形式的转载,转载请注明出处。
本站(WWW.)站内文章除注明原创外,均为转载、整理或搜集自网络。欢迎任何形式的转载,转载请注明出处。