sql server - How to check if a proposed T-SQL object name is valid or needs to be enclosed in square brackets -


my stored procedure may passed arbitrary string of characters @string varchar or nvarchar, no more 128 characters long.

the stored procedure needs use @string value object name, i.e. name of table, field, view or similar.

how can determine if value of @string supplied valid object name in - i.e. not reserved word , not contain invalid characters - or if require enclosure within (and escape of contained) square brackets in order make valid object name.

for example, "x", "foo" , "c:\temp\x.csv" valid object names (yes, i've used "c:\temp\x.csv" as-is) , can used unmodified, while "select", "ab]c" , "1_abc" not valid, , need changed "[select]", "[ab]]c]" , "[1_abc]"

i prefer solution doesn't attempt create object name , checks see if worked.

preference given answers applicable on wider range of sql server versions rather latest version, , shorter, less complex code preferred on longer, more complex code.

as example of problem led me ask question, sp can passed @name, might "c:\temp\x.csv" or "abc" or "select" or whatever. sp creates table, populates , then (so don't have use dynamic sql) changes it's name @name using sp_rename. need quotename(@name) @name = "select", not in other 2 cases, yielding (in ssms object explorer) tables "dbo.c:\temp\x.csv", "dbo.abc" , "dbo.select". however, need check if these objects exist before run rest of sp, , if quotename "c:\temp\x.csv", before pass new name sp_rename, appears in ssms object explorer "dbo.[c:\temp\x.csv]", , must use if object_id('[[c:\temp\x.csv]]]') not null determine exists, not if object_id('[c:\temp\x.csv]') not null.

when using sp_rename, new name object never needs escaped, use passed in @name value.

it's true object_id might want escaped name sometimes, since more direct test available that, again, doesn't require escaping, i'd suggest using test instead:

if exists(select * sys.tables name = @name) ... 

(or can query sys.objects instead, you)

i had envisaged using name in dynamic sql. in dynamic sql contexts, i'd suggest escaping name using quotename, rather trying determine if needs escaping.


Comments

Popular posts from this blog

scala - 'wrong top statement declaration' when using slick in IntelliJ -

c# - DevExpress.Wpf.Grid.InfiniteGridSizeException was unhandled -

PySide and Qt Properties: Connecting signals from Python to QML -