• Some users have recently had their accounts hijacked. It seems that the now defunct EVGA forums might have compromised your password there and seems many are using the same PW here. We would suggest you UPDATE YOUR PASSWORD and TURN ON 2FA for your account here to further secure it. None of the compromised accounts had 2FA turned on.
    Once you have enabled 2FA, your account will be updated soon to show a badge, letting other members know that you use 2FA to protect your account. This should be beneficial for everyone that uses FSFT.

MS SQL select inside an if

jseko

n00b
Joined
Jul 29, 2010
Messages
46
I am attempting to write the below query, but the column doesn't exist in photos table so MS SQL is reporting an error

Code:
if exists (select column_name from INFORMATION_SCHEMA.columns where table_name = 'audio' and column_name = 'aud_length')
	begin
	select * from audio where aud_length = 334
	end
if exists (select column_name from INFORMATION_SCHEMA.columns where table_name = 'photos' and column_name = 'aud_length')
	begin
	select * from photos where aud_length = 334
	end
 
Right, it's still parsing that query inside the if statement and finding that it's not valid before running the if statement.

Something like this might work.

Code:
if exists (select column_name from INFORMATION_SCHEMA.columns where table_name = 'audio' and column_name = 'aud_length')
	begin
	EXEC sp_executesql @statement = N'select * from audio where aud_length = 334'
	end
if exists (select column_name from INFORMATION_SCHEMA.columns where table_name = 'photos' and column_name = 'aud_length')
	begin
	EXEC sp_executesql @statement = N'select * from photos where aud_length = 334'
	end
 
Yes, you have to defer the execution past execution preparation because execution preparation includes binding names.

Seems like a pretty goofy thing to do, tho. Why not create the missing column, or create a view that contains the missing column, or ... ?
 
If you cannot create the missing column then you should make it conditional on a statement which returns the column names in the specified table.

EDIT:

Something like this:

IF EXISTS (select column_name from information_schema.columns
where table_name = 'YourTableName' and column_name ='QuestionableColumn')
 
Back
Top