December 21, 2006 at 4:51 pm
Hello,
In our application, we create tables at run time and the user provides the column names, data types. I need some kind of validation query for the column name so that it does not contain spaces, special characters, dashes; should not begin with numbers, or anything that SQL Server will not like excluding key words since I think I can overcome that problem with square brackets..
@ColName like '[0-9]%' or @ColName like '%-%' or @Colname like .....
Is that the way I have to do my checks??. or Is there any other simpler way?. or even a complex function with all possible checks that somebody has written to validate such names..
Any help will be appreciated.
Thanks,
Ganesh
December 21, 2006 at 7:15 pm
There is no simple way to validate...
It is OK to validate the name of the column...but first read the "Rules for Regular Identifiers" in BOL to validate the names...
Rules for Regular Identifiers
http://msdn2.microsoft.com/en-us/library/ms175874.aspx
MohammedU
Microsoft SQL Server MVP
December 22, 2006 at 9:31 am
Am I missing something? Wouldn't it be easier to use a regular expression at the application level to parse the user input?
December 22, 2006 at 1:01 pm
Read my article: Practical Uses of PatIndex: http://www.sqlservercentral.com/columnists/rdavis/practicalusesofpatindex.asp
You could use the sample code there with some slight modifications to get what you need. Use the NOT operator ( ^ ) for pattern matching to easily find if anything doesn't match your specifications. For example:
Declare
@val varchar(128)
Set
@val = 'i35iC4io'
Select
PatIndex('%[^0-9a-z[_]]%', @val)
The above is looking for any characters that do not match 0-9 or a-z or the underscore.
Dylan, you should never rely solely on the validation of the client applications.
December 22, 2006 at 2:31 pm
Sorry, I forgot that I don't need to escape the underscore with square brackets because it is already inside of square brackets.
Declare @val varchar(128)
Set @val = 'i&&35iC4io'
Select PatIndex('%[^0-9a-z_]%', @val)
December 22, 2006 at 2:54 pm
Thank you Robert!
Merry Christmas and Happy Holidays to all!
-Ganesh
December 22, 2006 at 4:25 pm
Ganesh,
I believe identifier name should not start with a number...
MohammedU
Microsoft SQL Server MVP
Viewing 8 posts - 1 through 7 (of 7 total)
You must be logged in to reply to this topic. Login to reply