Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 possible to select column using a variable

Author  Topic 

mike123
Master Smack Fu Yak Hacker

1462 Posts

Posted - 2009-01-06 : 11:06:02
Hi,

Trying to write a query here and wondering if the below is possible:

SELECT COUNT ( * ) WHERE @column_name > 30

--with @column_name being a column name

I dont think it is, but thought I'd try here before I give up.

Many thanks once again!
mike123

sakets_2000
Master Smack Fu Yak Hacker

1472 Posts

Posted - 2009-01-06 : 11:08:05
using dynamic sql, it is.
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2009-01-06 : 11:14:46
this is not a good approach. can you tell why you want to do this? why is column determined dynamically?
Go to Top of Page

thiyagu_rind
Starting Member

46 Posts

Posted - 2009-01-07 : 00:57:18
Hi Dear,

Yeah you can do that as below it will work

Query:

SELECT count(*) FROM EP_CLEARANCE_TYPE
WHERE CLT_TYPE_ID >10

My Suggestion is do the same but like this.

Query:
SELECT SUM(1) FROM EP_CLEARANCE_TYPE
WHERE CLT_TYPE_ID >10



Regards
Thiyagarajan
Go to Top of Page

Jai Krishna
Constraint Violating Yak Guru

333 Posts

Posted - 2009-01-07 : 02:04:21
Try This using Dynamic SQL but this is not efficient

DECLARE @str VARCHAR(8000)

SELECT @str = 'SELECT COUNT ( * ) FROM Urtable WHERE'+ @column_name+' > 30'

EXEC(@str)




Jai Krishna
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2009-01-07 : 03:19:37
quote:
Originally posted by thiyagu_rind

Hi Dear,

Yeah you can do that as below it will work

Query:

SELECT count(*) FROM EP_CLEARANCE_TYPE
WHERE CLT_TYPE_ID >10

My Suggestion is do the same but like this.

Query:
SELECT SUM(1) FROM EP_CLEARANCE_TYPE
WHERE CLT_TYPE_ID >10



Regards
Thiyagarajan



did you read the original question?
Go to Top of Page

mike123
Master Smack Fu Yak Hacker

1462 Posts

Posted - 2009-01-07 : 06:39:02
Hey Visakh16,

Apprecaite the help. Actually I have decided to avoid this approach as I don't like dynamic SQL either :) I have done it without.

Thanks for the advice!
mike123
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2009-01-07 : 09:51:50
quote:
Originally posted by mike123

Hey Visakh16,

Apprecaite the help. Actually I have decided to avoid this approach as I don't like dynamic SQL either :) I have done it without.

Thanks for the advice!
mike123


Welcome

Go to Top of Page
   

- Advertisement -