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

Dynamic SQL for Primary Key Declaration

$
0
0

Requirement

Create primary key constraint on tables which have been dynamically created. Primary keys are supposed to be created in line with the information from the metadata table. Some tables have composite primary keys while some have primary keys made up from just one column only, and yet again others don’t have any primary key constraints at all.

Sample Metadata Table

CREATETABLE#Stage_Primary_Key_Column_List(ID INTIDENTITY(1,1),Column_NameVARCHAR(255),FlagINT)

INSERTINTO#Stage_Primary_Key_Column_List(Column_Name,Flag)

VALUES ('ETL_Id',0),

             ('Row_Id',0),

             ('File_Partition_Id',0)

Sample outcome that I would like from the metadata table

(ETL_Id, Row_Id, File_Partition_Id)

My sample query which I would like to be dynamic:

SELECT'('+(SELECT Column_NameFROM #Stage_Primary_Key_Column_ListWHERE ID= 1)+', '

      +(SELECTColumn_NameFROM #Stage_Primary_Key_Column_ListWHERE ID= 2)+', '

      +(SELECTColumn_NameFROM #Stage_Primary_Key_Column_ListWHERE ID= 3)+')'

 

Many thanks,


Mpumelelo


Viewing all articles
Browse latest Browse all 23857

Trending Articles



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