Added some changes..fixed schema syntax, used quotename, changed code to use union all with SELECTs
DECLARE @TABLE_NAME sysname, @TABLE_SCHEMA sysname
SELECT @TABLE_SCHEMA='dbo'
SELECT @TABLE_NAME='Media'
SET NOCOUNT ON
DECLARE @CMD nvarchar(max)
DECLARE @INSCMD nvarchar(max)
DECLARE @INSVAL varchar(max)
DECLARE