0

I'm trying to set the columnName, databaseName, schemaName etc. dynamically based on a temporary table but cant seem to make it work. i've tried below?

Create Table #test(databaseName varchar(128), schemaName varchar(128), columnName varchar(128), datatypeName varchar(128));

INSERT INTO #test ('testDatabase', 'testSchema', 'testTable', 'priceColumn');

SELECT
Case
    WHEN DataType = 'int'
    THEN SELECT MAX(ColumnName) FROM Concat(databaseName, '.', schemaName, '.', tableName)
    ELSE 0
end
FROM #test;

DROP TABLE #test;

the expected result is that this below subquery take each line in the row in #test table and then query based on these values so it return the maxPrice from that table

SELECT MAX(ColumnName) FROM Concat(databaseName, '.', schemaName, '.', tableName)
6
  • Am I missing something? 1. You create the temp table. 2. You Select from the temp table. 3. Drop the temp table. But you never insert any rows into it. Commented Apr 27, 2017 at 17:51
  • i do that in another select statement which is not included due to the size and complexity of it. i could create test insert though. Commented Apr 27, 2017 at 17:52
  • It is hard to tell. It appears the goal is to find the a.b.c nomenclature name of the last field of a given data type. We need clarification. Commented Apr 27, 2017 at 17:52
  • Understood. Can you show some sample data and expected results? Commented Apr 27, 2017 at 17:52
  • 1
    ...Just a side note, If you use @test instead of #test you don't have to drop the temp table as it lives in memory and is automatically de-allocated when the statement loses scope. Commented Apr 27, 2017 at 17:59

1 Answer 1

1

Are you trying to aggregate on a calculated field while preserving the query flow?

You can try something like this.

SELECT 
    MAX(FullName)
FROM
(
    SELECT
         FullName = databaseName+ '.' + schemaName + '.' + columnName,
         *
    FROM
        @test
) AS A
WHERE
    DataTypeName='int'

Another example

SELECT 
    MAX(FullNameInt),
    MAX(FullNameOther)
FROM
(
    SELECT
        FullNameInt   = CASE WHEN DataTypeName='int' THEN  databaseName+ '.' + schemaName + '.' + columnName ELSE NULL END,
        FullNameOther = CASE WHEN DataTypeName<>'int' THEN databaseName+ '.' + schemaName + '.' + columnName ELSE NULL END,
         *
    FROM
        @test
) AS A
Sign up to request clarification or add additional context in comments.

2 Comments

the problem is here this does not enable to add more dataTypeNames like in a case statement
I updated my answer, however, I no longer think I understand what it is you are attempting.

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.