Home  >  Article  >  Database  >  mssql 存储过程根据表名和索引获取需要的列名

mssql 存储过程根据表名和索引获取需要的列名

WBOY
WBOYOriginal
2016-06-07 17:48:181045browse

本教程涉及到了raiserror函数,有需要的朋友可以参考一下。

RAISERROR ( { msg_id | msg_str | @local_variable }
{ ,severity ,state }
[ ,argument [ ,...n ] ]
)
[ WITH option [ ,...n ] ]
参数说明:
 
第一个参数:{ msg_id | msg_str | @local_variable }
msg_id:表示可以是一个sys.messages表中定义的消息代号;
使用 sp_addmessage 存储在 sys.messages 目录视图中的用户定义错误消息号。
用户定义错误消息的错误号应当大于 50000。

msg_str:表示也可以是一个用户定义消息,该错误消息最长可以有 2047 个字符;
(如果是常量,请使用N'xxxx',因为是nvarchar的)
当指定 msg_str 时,RAISERROR 将引发一个错误号为 5000 的错误消息。

@local_variable:表示也可以是按照 msg_str 方式的格式化字符串变量。

第二个参数:severity
用户定义的与该消息关联的严重级别。(这个很重要)
任何用户都可以指定 0 到 18 之间的严重级别。
[0,10]的闭区间内,不会跳到;
如果是[11,19],则跳到catch;
如果[20,无穷),则直接终止连接;

第三个参数:state
如果在多个位置引发相同的用户定义错误,
则针对每个位置使用唯一的状态号有助于找到引发错误的代码段。

介于 1 至 127 之间的任意整数。(state 默认值为1)
当state 值为 0 或大于 127 时会生成错误!

第四个参数:argument
用于代替 msg_str 或对应于 msg_id 的消息中的定义的变量的参数。

第五个参数:option
错误的自定义选项,可以是下表中的任一值:
LOG :在错误日志和应用程序日志中记录错误;
NOWAIT:将消息立即发送给客户端;
SETERROR:将 @@ERROR 值和 ERROR_NUMBER 值设置为 msg_id 或 50000

 代码如下 复制代码

create proc p_sword_getblcolumn
(
@tblName varchar(200),
@fromIndex int,
@toIndex int,
@columnName varchar(3000) output
)
as
begin
 declare @tempColumn varchar(3000)
 declare @errMsg varchar(200)
 declare @i int
 set @i=1
 set @columnName=''
 set @errMsg=''
 declare tempColumnCur cursor for
  syscolumns.name from syscolumns  join sysobjects on syscolumns.id = sysobjects.id
 where sysobjects.name =@tblName order by syscolumns.colorder
 
 open tempColumnCur
 fetch next from tempColumnCur into @tempColumn
 while @@FETCH_STATUS=0
  begin
   if(@fromIndex=0 and @toIndex=0)
    begin
     set @columnName=@columnName+','+@tempColumn
    end
   if(@fromIndex=0 and @toIndex0)
    begin
     if(@i       set @columnName=@columnName+','+@tempColumn
    end
   else if(@fromIndex 0 and @toIndex=0)
    begin
     if(@i>=@fromIndex)
      set @columnName=@columnName+','+@tempColumn
    end
   else if(@i>=@fromIndex and @i     begin
      set @columnName=@columnName+','+@tempColumn
    end
   set @i=@i+1 
   print @i
   fetch next from tempColumnCur into @tempColumn
  end
 close tempColumnCur
 deallocate tempColumnCur
 set @columnName=SUBSTRING(@columnName,2,len(@columnName))
 print @columnName
 if(@@ERROR0)
 begin
  set @errMsg='get column error '
  goto errorproc
 end
 else
  return 0
end

errorproc:
begin
 raiserror(@errMsg,16,1)
 return 1
end

go

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn