开发者

Find reserved keywords in TSQL

开发者 https://www.devze.com 2023-03-13 03:57 出处:网络
I am not sure if there is any built-in function in sql server 2008 that will tell whether it is reserved keyword or not.

I am not sure if there is any built-in function in sql server 2008 that will tell whether it is reserved keyword or not.

The reason I wanted to do this is because I find sometimes the column names are using the same name as the reserved keywords, for example, a column called 'desc', 'user', 'state', etc, which then we have to wrap them with square brackets ([desc], [user], [state]) to be able to query the columns correctly.

If such a built-in function does exist, then we probably can do

if isReservedKeyword (@name) = true
  set @column = REPLACE(@column, @name, '[' + @name+ ']')
else
 开发者_C百科 set @column = @name


Reserved words are documented here:
http://msdn.microsoft.com/en-us/library/ms189822.aspx

That list is exhaustive, but it's not so long that you couldn't just re-enter those into your own database table to check against.


There is a built in function that will take care of this, and also 'unusual' characters: QUOTENAME :

Returns a Unicode string with the delimiters added to make the input string a valid SQL Server delimited identifier.

The following example takes the character string abc[]def and uses the [ and ] characters to create a valid SQL Server delimited identifier.

SELECT QUOTENAME('abc[]def')

Here is the result set.

[abc[]]def]

(1 row(s) affected)

Notice that the right bracket in the string abc[]def is doubled to indicate an escape character.


Just put brackets around every column. That way you ensure that even reserved words are taken care of.

0

精彩评论

暂无评论...
验证码 换一张
取 消