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
  • 61,578
  • 25
  • 134
  • 173
aydjay
  • 858
  • 11
  • 25

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
  • 153,850
  • 22
  • 249
  • 325
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
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
  • 153,850
  • 22
  • 249
  • 325