Variable in Select Stmt

Posted on 2009-04-22
Last Modified: 2012-05-06
Hello Experts,

How can I used a variable for the column name in the select statement?

declare	  @roll_id				int	

		, @field_to_correct_value	varchar(100)

		, @roll_id_number	int

		, @field_to_correct	varchar(100)

select @roll_id 			= (select max(roll_id) from hcad..rolls_diary)	

select @field_to_correct_value = 'owner_name_1'  --this is a column name

select @roll_id_number = @roll_id

select @roll_id_number, strap, '@field_to_correct', owner_name_1, @field_to_correct_value

  from history.dbo.pcr_history

Open in new window

Question by:thewayne73
    LVL 142

    Accepted Solution

    no, unless you used dynamic sql.
    LVL 57

    Expert Comment

    by:Raja Jegan R
    Just replace this part given below:

    select @roll_id_number, strap, '@field_to_correct', owner_name_1, @field_to_correct_value
      from history.dbo.pcr_history

    select @roll_id_number as roll_id_number, strap, @field_to_correct as field_to_correct, owner_name_1, @field_to_correct_value
      from history.dbo.pcr_history

    Featured Post

    Free Trending Threat Insights Every Day

    Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

    Join & Write a Comment

    'Between' is such a common word we rarely think about it but in SQL it has a very specific definition we should be aware of. While most database vendors will have their own unique phrases to describe it (see references at end) the concept in common …
    Use this article to create a batch file to backup a Microsoft SQL Server database to a Windows folder.  The folder can be on the local hard drive or on a network share.  This batch file will query the SQL server to get the current date & time and wi…
    Illustrator's Shape Builder tool will let you combine shapes visually and interactively. This video shows the Mac version, but the tool works the same way in Windows. To follow along with this video, you can draw your own shapes or download the file…
    Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…

    755 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    20 Experts available now in Live!

    Get 1:1 Help Now