字符是否为SQL的保留字
要想知道字符是否为MS SQL Server保留字,那我们必须把SQL所有保留字放在一个数据集中。然后我们才能判断所查找的字符是否被包含在数据集中。
MS SQL Server保留字:
DECLARE @ReservedWords VARCHAR(2000) = 'add,all,alter,and,any,as,asc,authorization,avg,backup,begin,between,break,browse,bulk,by,cascade,case,check,checkpoint,close,clustered,coalesce,column,commit,committed,compute,confirm,constraint,contains,containstable,continue,controlrow,convert,count,create,cross,current,current_date,current_time,current_timestamp,current_user,cursor,database,dbcc,deallocate,declare,default,delete,deny,desc,disk,distinct,distributed,double,drop,dummy,dump,else,end,errlvl,errorexit,escape,except,exec,execute,exists,exit,fetch,file,fillfactor,floppy,for,foreign,freetext,freetexttable,from,full,goto,grant,group,having,holdlock,identity,identity_insert,identitycol,if,in,index,inner,insert,intersect,into,is,isolation,join,key,kill,left,level,like,lineno,load,max,min,mirrorexit,national,nocheck,nonclustered,not,null,nullif,of,off,offsets,on,once,only,open,opendatasource,openquery,openrowset,option,or,order,outer,over,percent,percision,perm,permanent,pipe,plan,prepare,primary,print,privileges,proc,procedure,processexit,public,raiserror,read,readtext,reconfigure,references,repeatable,replication,restore,restrict,return,revoke,right,rollback,rowcount,rowguidcol,rule,save,schema,select,serializable,session_user,set,setuser,shutdown,some,statistics,sum,system_user,table,tape,temp,temporary,textsize,then,to,top,tran,transaction,trigger,truncate,tsequal,uncommitted,union,unique,update,updatetext,use,user,values,varying,view,waitfor,when,where,while,with,work,writetext,'
此时,我们可以把这字符串拆分插入一张表中:
CREATE TABLE [dbo].[ReservedWordOfSql] ( [KeyWork] NVARCHAR(40) ) GO
WHILE CHARINDEX(',',@ReservedWords) <>0 BEGIN DECLARE @v NVARCHAR(40) = LTRIM(RTRIM(SUBSTRING(@ReservedWords,1,CHARINDEX(',',@ReservedWords) - 1))) INSERT INTO [dbo].[ReservedWordOfSql] ([KeyWork]) VALUES (@v) SET @ReservedWords = STUFF(@ReservedWords,1,CHARINDEX(',',@ReservedWords),N'') END GO
举例说明:
其实,我们可以写成一个自定义函数:
CREATE FUNCTION [dbo].[svf_IsReservedWord] ( @searchword NVARCHAR(40) ) RETURNS BIT AS BEGIN DECLARE @exists BIT = 1 IF NOT EXISTS(SELECT TOP 1 1 FROM [dbo].[ReservedWordOfSql] WHERE [KeyWork] = @searchword) SET @exists = 0 RETURN @exists END GO
执行函数,将得到相同的结果: