Jump to content
Xtreme .Net Talk

Recommended Posts

Posted

I need to do a simple query retrieving the value from a particular column of the database...ie

 

SELECT myColumn

FROM myTable

WHERE user_id = 100

 

But - the "myColumn" can vary and cant be hardcoded, so i'm passing the column name as a nvarchar parameter.

 

exec('select ' + @colname + ' FROM myTable where user_id = 100')

 

But...i then need to do something with that value that gets returned. How do i get hold of it? I cant seem to declare another variable and set it when using the "exec".

 

Cheers.

van

Grant me the serenity to accept the things I cannot change, the courage to change the things I cannot accept and the wisdom to hide the bodies of those people I had to kill today cos they pi**ed me off.
  • *Experts*
Posted

Haven't tried this in awhile, but I think you need to use a temp table. Try something like:

CREATE TABLE #temp ([iD] int)

exec('insert into #temp select ' + @colname + ' FROM myTable where user_id = 100')

SELECT [iD] FROM #temp

 

-nerseus

"I want to stand as close to the edge as I can without going over. Out on the edge you see all the kinds of things you can't see from the center." - Kurt Vonnegut
Posted

perfect!

 

just had to add a DROP TABLE #temp to the end.

 

Cheers - you're a star!

Grant me the serenity to accept the things I cannot change, the courage to change the things I cannot accept and the wisdom to hide the bodies of those people I had to kill today cos they pi**ed me off.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...