0

I am trying to retract a column from a table by knowing the header name of the column that I want to retrieve.

select @sName
from VPDW.dbo.Fact_Email_MW100
where VesselID = 3763 
  and (cast(UTClogTime as date) >= cast(DateAdd(day, -1, GETUTCDATE()) as date))

where

Declare @sName nvarchar(max);

holds the string name of the column that I want to extract from my table.

3
  • You need to use dynamic SQL for this. Commented Jul 22, 2018 at 15:19
  • Could you provide an easy example of this? Not too familiar with SQL yet. Commented Jul 22, 2018 at 15:21
  • @GordonLinoff, with XML's abilities to resolve generically defined queries this does not demand for dyanmic SQL and can be solved fully inline. I placed an answer... Commented Jul 23, 2018 at 7:25

2 Answers 2

3

The whole query needs to be dynamic in order to achieve what you're trying to do. That is, you have to build the SQL and then execute it. Consider something like the following (not tested):

declare @sName nvarchar(max)
declare @sql nvarchar(max)

set @sName = 'some_column'

set @sql = 'select ' + @sName + ' from VPDW.dbo.Fact_Email_MW100 where VesselID = 3763 and (cast(UTClogTime as date) >= cast(DateAdd(day,-1,GETUTCDATE()) as date))'
print @sql

exec sp_sqlexec  @sql
Sign up to request clarification or add additional context in comments.

4 Comments

Worked flawlessly. Thanks!
If you don't want to meet Bobby Tables then the column name should be validated against the sys.columns view for the target table. The best practice when assembling object names into dynamic SQL statements is to use QuoteName() to avoid problems with odd names, e.g. New Table with a space or reserved words like From.
@HABO correct and important to mention! Or you can use XML's generic queries.
William, The whole query needs to be dynamic... There is a non-dynamic approach using XML (see my answer).
1

Sometimes one cannot use dynamic SQL (in VIEWs, iTVFs). In such cases you can uses XML's abilities to deal with generic queries:

DECLARE @ColName VARCHAR(100)='name';

SELECT
(
    SELECT TOP 1 * 
    FROM sys.objects
    FOR XML PATH('row'),TYPE
).value('(/row/*[local-name()=sql:variable("@ColName")]/text())[1]','nvarchar(max)') AS ValueAtColumnName;

This will get one row of sys.objects and return the value for the column name.

For your query this would look like

Declare @sName nvarchar(max);
SELECT
(
    select *
    from VPDW.dbo.Fact_Email_MW100
    where VesselID = 3763 
      and (cast(UTClogTime as date) >= cast(DateAdd(day, -1, GETUTCDATE()) as date))

).value('(/row/*[local-name()=sql:variable("@sName")]/text())[1]','nvarchar(max)') AS ValueAtColumnName;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.