Pரதீப்
Pரதீப்

Reputation: 93694

Reserved Keyword in Where clause

Consider the following setup

create table #test([user] varchar(10))
insert into #test([user]) values ('test')

when user column is enclosed with square brackets then the query returns result else it does not return result even though there is a matching record

SELECT *
FROM   #test WHERE [user] = 'test' -- returns record

SELECT *
FROM   #test WHERE user = 'test' --did not return record

This begs the following two questions

  1. Why is the first query works and the second query does not ?
  2. Why the reserved keyword is allowed to use in where clause without escaping it ?

Upvotes: 2

Views: 805

Answers (2)

Dgan
Dgan

Reputation: 10285

As per MS Docs

user without brackets will work as function which returns database user name

if you check with following query it will return records

SELECT *
FROM   #test WHERE user = 'dbo'

When we Use [] Square brackets it sql server will treat as non reserve keyword like user defined column name,table name,function name.etc

Upvotes: 5

HoneyBadger
HoneyBadger

Reputation: 15140

User is a reserved keyword for a reason. Try this:

SELECT User;

For me, it returns a single row with value dbo.

So the query without escaping user is perfectly valid, it just doesn't fit the value you are comparing it to.

Upvotes: 7

Related Questions