Hi @Nishan Ratna Try this query:
declare @sourcetablename nvarchar(max) = N'[dbo].[AAG00200]'
declare @targettablename nvarchar(max) = N'[dbo].[AAG00200_Test]'
declare @PKname nvarchar(max)
declare @sql nvarchar(max)
set @sql = N'
IF OBJECT_ID(''tempdb.dbo.#TempTable'', ''U'') IS NOT NULL
DROP TABLE #TempTableName
select * into #TempTable from '+@sourcetablename+'
SELECT @PKname = Index_name FROM #TempTable where is_primary_key = 1'
EXEC sp_executesql @sql,N'@PKname nvarchar(max) OUTPUT',@PKname = @PKname OUTPUT
SET @sql=N'ALTER TABLE '+@targettablename+' ADD CONSTRAINT '+@PKname+' PRIMARY KEY (ACTINDX)'
EXEC sp_executesql @sql
Best regards, Cosmog Hong
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment". Note: Please follow the steps in our Documentation to enable e-mail notifications if you want to receive the related email notification for this thread.