Quantcast
Channel: Transact-SQL forum
Viewing all articles
Browse latest Browse all 23857

Write dynamic query using User-Defined Table Types

$
0
0

Hi,

I have a User-Defined Table Types ( @SelectedDBDt AS dbo.SelectedDBList READONLY) and sending values from coding .

Let assume this is the data for @SelectedDBDt  :

DBName

NorthWind

NorthWind1

NorthWind2

Telerik

Telerik1

Telerik2

EFMS

EFMS1

EFMS2


Based on above values I would like to Union queries for 6 databases.

SELECT AddNo From NorthWind
UNION
SELECT AddNo FROM Server1.NorthWind1
UNION
SELECT AddNo FROM Server2.NorthWind2
UNION
SELECT AddNo From Telerik
UNION
SELECT AddNo FROM Server1.Telerik1
UNION
SELECT AddNo FROM Telerik2
UNION
SELECT AddNo From EFMS
UNION
SELECT AddNo FROM EFMS1
UNION
SELECT AddNo FROM EFMS2


If @SelectedDBDt contains only 3 records like 'NorthWind', 'Telerik' and 'EFMS' then union only 3 queries for 3 databases.

SELECT AddNo From NorthWind
UNION
SELECT AddNo FROM Telerik
UNION
SELECT AddNo FROM EFMS



If @SelectedDBDt contains only 2 records like 'NorthWind1', 'EFMS' then union only 2 queries for 2 databases.

SELECT AddNo From NorthWind1
UNION 
SELECT AddNo FROM EFMS

 Please help to write query based on values  from @SelectedDBDt


Thank you.





Viewing all articles
Browse latest Browse all 23857

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>