字符是否為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
Source Code

 

 

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
Source Code

 

舉例說明:

 

其實,我們可以寫成一個自定義函數:

 

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
Source Code

 

執行函數,將得到相同的結果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM