| Author |
Topic |
|
CSK
Constraint Violating Yak Guru
489 Posts |
Posted - 2007-11-15 : 09:07:30
|
| Gurus,Why i am not getting error in the follwoing query. The data1 column doesnt exits in tbl2 but it is not giving the error CREATE TABLE TBL1 ( Id1 int IDENTITY(1,1) PRIMARY KEY, data1 int ) CREATE TABLE TBL2(Id int IDENTITY(1,1) PRIMARY KEY, Id1 int, data2 int ) Select * from TBL1 Where Id1 IN (Select data1 from TBL2) |
|
|
jamie
Aged Yak Warrior
542 Posts |
Posted - 2007-11-15 : 09:22:07
|
| because in tbl2 you have the field data2 not data1. |
 |
|
|
jamie
Aged Yak Warrior
542 Posts |
Posted - 2007-11-15 : 09:23:01
|
| ignore that.:) |
 |
|
|
elancaster
A very urgent SQL Yakette
1208 Posts |
Posted - 2007-11-15 : 09:25:09
|
quote: jamiebecause in tbl2 you have the field data2 not data1.
i misread it at first too. OP is saying they DON'T get an error. i tried it and was surprised too actually. i can only guess that it's somehow 'recognised' it as valid from tbl1. not come accross this before thoughEm |
 |
|
|
elancaster
A very urgent SQL Yakette
1208 Posts |
Posted - 2007-11-15 : 09:28:24
|
| it does throw an error if you prefix it with the table name ... i.e. tbl2.data1Em |
 |
|
|
khtan
In (Som, Ni, Yak)
17689 Posts |
Posted - 2007-11-15 : 09:28:26
|
bacause data1 is a valid column in TBL1If you prefix the column name with table name or alias, you will see if return you an errorSelect * from TBL1 Where Id1 IN (Select t2.data1 from TBL2 t2) KH[spoiler]Time is always against us[/spoiler] |
 |
|
|
evilDBA
Posting Yak Master
155 Posts |
Posted - 2007-11-15 : 09:28:34
|
| Correct, this is an SQL trap.In a subquery, all columns from the upper table are still visible and accesible |
 |
|
|
khtan
In (Som, Ni, Yak)
17689 Posts |
Posted - 2007-11-15 : 09:30:41
|
also try thisCREATE TABLE TBL1( Id1 int IDENTITY(1,1) PRIMARY KEY, data1 int)CREATE TABLE TBL2( Id int IDENTITY(1,1) PRIMARY KEY, Id1 int, data2 int )INSERT INTO TBL1 (data1)SELECT 1 UNION ALLSELECT 2 UNION ALLSELECT 30INSERT INTO TBL2 (Id1, data2)SELECT 100, 200SELECT * FROM TBL1 WHERE Id1 IN (SELECT data1 FROM TBL2)DROP TABLE TBL1DROP TABLE TBL2 KH[spoiler]Time is always against us[/spoiler] |
 |
|
|
CSK
Constraint Violating Yak Guru
489 Posts |
Posted - 2007-11-15 : 09:30:43
|
| Yeah while giving ailas i am not getting error. Without alias its throwing error.ThanksKrishna |
 |
|
|
khtan
In (Som, Ni, Yak)
17689 Posts |
Posted - 2007-11-15 : 09:31:49
|
So it is good practice to always prefix your column name with table name or table alias. KH[spoiler]Time is always against us[/spoiler] |
 |
|
|
CSK
Constraint Violating Yak Guru
489 Posts |
Posted - 2007-11-15 : 09:32:26
|
| you are 100 % right Khtan.ThanksKrishna |
 |
|
|
khtan
In (Som, Ni, Yak)
17689 Posts |
Posted - 2007-11-15 : 09:34:08
|
quote: Originally posted by CSK Yeah while giving ailas i am not getting error. Without alias its not throwing error.ThanksKrishna
KH[spoiler]Time is always against us[/spoiler] |
 |
|
|
|