Link to home
Create AccountLog in
Avatar of milani_lucie
milani_lucieFlag for United States of America

asked on

QUOTENAME help needed - SQL Server

Hi,

I have the following command:

SELECT QUOTENAME('abc[]def')

It returns me

[abc[]]def]  -- Carefully look at the braces

There is a meaning if it returns me

[abc[]def]  -- Carefully look at the braces

Can you please explain to me why SQL Server is returning [abc[]]def] as result ?

Thanks
SOLUTION
Avatar of JestersGrind
JestersGrind
Flag of United States of America image

Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
ASKER CERTIFIED SOLUTION
Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
SOLUTION
Avatar of Guy Hengel [angelIII / a3]
Guy Hengel [angelIII / a3]
Flag of Luxembourg image

Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account

So basically let's say that you are creating a query dynamically
if you do

set @strSQL = 'select col1, col2, [abc[]def] from yourtable'

This will fail, because SQL will think that the column name is [abc[]. So to solve the problem you need to escape the ] character so that SQL understand that it's a literal character. The way of doing that is by repeating the character.

set @strSQL = 'select col1, col2, [abc[]]def] from yourtable' --this will be ok.
Now I wouldn't define any columns with any special characters such us the brackets. Just my two cents.