How to escape square brackets inside square bracke

2019-01-26 05:52发布

问题:

I have some dynamic SQL that generates column names. A quick example might be something like this:

SELECT dbo.getSomething(123) [Eggs[scrambled] or Bacon[fried]]

The final column name should be this:

Eggs[scrambled] or Bacon[fried]

If I try to run this it will error on the word OR (even if I replace it with xyz it still errors on that token). The problem is fixed if I take out the inner sets of square brackets. So my conclusion is that you can't nest square brackets unless you somehow escape them.

How do I escape them in this case?

回答1:

You can use the quotename function to see the proper escaping.

select quotename('Eggs[scrambled] or Bacon[fried]') 

Returns

[Eggs[scrambled]] or Bacon[fried]]]

So all closing square brackets need to be doubled up.



回答2:

Hang a ] on the end of inline []

   SELECT [Eggs[scrambled]] or Bacon[fried]]] FROM Yummy


回答3:

SET QUOTED_IDENTIFIER is ON by default so no need to escape anything

SELECT 1 AS "[Eggs[scrambled] or Bacon[fried]]"


回答4:

In an SSIS SQL statement querying an excel sheet you must substitute square brackets for parenthesis to select individual columns. For example to select "My Column [Great Column]" you would SELECT [My Column (Great Column)] FROM [$A1:AX10000]