Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6620315
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 25, 20262026-05-25T21:04:57+00:00 2026-05-25T21:04:57+00:00

I have worked out how to pivot a row from a table using PIVOT

  • 0

I have worked out how to pivot a row from a table using PIVOT in SQL Server 2005, however, I dont like the method as I have had to hard code the columns (Currency Codes) and I would like to have the Pivot select the columns dynamically.

As an Example, imagine you have the following table (called OrderCash):

OrderID   CAD     CHF     EUR     GBP     JPY     NOK     USD
40        0       0       128.6   552.25  -9232   0       -4762
41        0       0       250.2   552.25  -9232   0       -4762
42        233.23  0       552.25  -9232   0       0       -4762

The hard-coded Pivot statement is:

SELECT  OrderID,
        CurrCode + 'GBP CURNCY' AS Ticker,
        Cash AS Position
FROM
(
    SELECT OrderID,
        CAD,
        CHF,
        EUR,
        GBP,
        JPY,
        NOK,
        USD
    FROM OrderCash
) p
UNPIVOT
(
    Cash FOR CurrCode IN 
    (CAD, CHF, EUR, GBP, JPY, NOK, USD)
) AS unpvt
WHERE Cash != 0
And OrderID = 42

This would return the following required table:

OrderID   Ticker           Position
42        CADGBP CURNCY    233.23
42        EURGBP CURNCY    552.25
42        GBPGBP CURNCY    -9232
42        USDGBP CURNCY    -4762

The problem arrises further down the road when someone tells me I need to have AUD as a new currency in the table?

FYI, I have a table-valued function that returns all the column names as a table:

ALTER FUNCTION [dbo].[GetTableColumnNames]
        (
        @TableName NVARCHAR(250),
        @StartFromColumnNum INT
        )

    RETURNS @ReturnTable TABLE
        (
        ColName NVARCHAR(250)
        )
AS

BEGIN
    INSERT INTO @ReturnTable
        SELECT COLUMN_NAME from information_schema.columns
        WHERE TABLE_NAME = @TableName
            AND ORDINAL_POSITION >= @StartFromColumnNum
        ORDER BY ORDINAL_POSITION

    RETURN
END 

So the easy bit has been done (SELECT * FROM dbo.GetTableColumnNames(‘OrderCash’,2)), the problem I am having is inserting this ‘dynamic’ table with the column names into the Pivot?

Any help would be much appreciated.
Many thanks
Bertie.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-25T21:04:58+00:00Added an answer on May 25, 2026 at 9:04 pm

    I’ve done a few too many of these dynamic queries of late… (my columns shift by client by month). Here’s one way to do it–no testing, no debugging, there might be a few bugs to iron out:

    DECLARE
      @Command     nvarchar(max)
     ,@ColumnList  nvarchar(max)
     ,@OrderId     int
     ,@Debug       bit
    
    
    --  Build a comman-delimited list of the columns
    SELECT @ColumnList = isnull(@ColumnLIst + ',', , '') + ColName
     from dbo.GetTableColumnNames('OrderCash', 2)
    
    
    --  Insert the list of columns in two places in your query
    SET @Command = replace('
    SELECT  OrderID, 
            CurrCode + ‘‘GBP CURNCY’‘ AS Ticker, 
            Cash AS Position 
    FROM 
    ( 
        SELECT OrderID, <@ColumnList>
        FROM OrderCash 
    ) p 
    UNPIVOT 
    ( 
        Cash FOR CurrCode IN  
        (<@ColumnList>) 
    ) AS unpvt 
    WHERE Cash != 0 
    And OrderID = @OrderId
    ', '<@ColumnList>', @ColumnList)
    
    
    --  Always include something like this!
    IF @Debug = 1
        PRINT @Command
    
    --  Using sp_executeSQL over EXECUTE (@Command) allows you execution
    --  plan resuse with parameter passing (this is the part you may need
    --  to debug on a bit, but it will work)
    EXECUTE sp_executeSQL @Command, N'@OrderId int', @OrderId
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

We have worked out how to databind entites with sql like syntax: var countryQuery
I have an iFrame and have worked out how to clone it using jQuery:
I have worked out how to detect touching on an object using glReadPixels but
I have a JavaScript-based timeline which needs to use data from an SQL server.
I have finally worked out how to get stdin and stdout to pipe between
I've worked out most of the code and have several game classes. The one
I have worked a bit with Django and I quite like its project/applications model
I have worked out how to fade an element in: Click here to view
I have worked out how to calculate the correlation coefficient between two fields if
In the solution I have worked out to this question => General type conversion

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.