0

I have a query that should be ignoring my applications system columns, I can't explain why it's not detecting the following column as a system column. A system column starts with DW_ and could contain a space, hence the use of quotename.

 DECLARE @columnName NVARCHAR(max)

 set @columnName = Quotename('DW_ID')

 print @columnName

 IF (@columnName LIKE 'DW_%')
    print 'system column'
 else
    print 'non system column'

I would expect the above query to tell me it's a system column but it tells me it's a non system column.

nhgrif
  • 60,018
  • 25
  • 128
  • 167
aydjay
  • 737
  • 8
  • 23

2 Answers2

2

quotename() adds square braces:

select Quotename('DW_ID')

[DW_ID]

Here is a little SQL Fiddle.

So you would want to include these in your pattern matching. Something like:

IF (@columnName LIKE '[[]DW_%]')
Patrick Hofman
  • 148,824
  • 21
  • 237
  • 306
Gordon Linoff
  • 1,198,228
  • 53
  • 572
  • 709
1

First, Quotename adds brackets to DW_ID, which makes that DW_% will never match on [DW_ID].

Second, you should match on the brackets too. Since brackets have a special meaning in a like you need to escape them:

DECLARE @columnName NVARCHAR(max)

set @columnName = Quotename('DW_ID')
-- @columnName is [DW_ID] now

print @columnName

IF (@columnName LIKE '[[]DW_%]')
   print 'system column'
else
   print 'non system column'
Community
  • 1
  • 1
Patrick Hofman
  • 148,824
  • 21
  • 237
  • 306