Thursday, February 26, 2015

HOW TO GET ALL COLUMN DATA IN A SINGLE ROW BY USING XML PATH & STUFF TRICK

DECLARE @CodeNameString varchar(100)

SELECT 
   @CodeNameString = STUFF( (SELECT ',' + CodeName 
                             FROM dbo.AccountCodes 
                             ORDER BY Sort
                             FOR XML PATH('')), 
                            1, 1, '')
 
EXAMPLE: to get dynamic sript in a single column and 
         execute 
        some other way looping throw row by row execution

 If Exists (select * from sysobjects where id = object_id(N'[dbo].[table_list]') 
and OBJECTPROPERTY(id, N'IsUserTABLE') = 1)
DROP TABLE table_list

CREATE TABLE [table_list]
(    
    
    createtab NVARCHAR(MAX)
)
INSERT INTO table_list(createtab)
SELECT ' IF EXISTS(SELECT * FROM  Staging_Data.dbo.sysobjects 
WHERE ID = Object_Id(N''dbo.tbl_tkn_'+ CAST(token_schema_details_id as varchar(5)) + ''' ) 
and OBJECTPROPERTY(id, N''IsUserTable'') = 1)'+CHAR(10)+'BEGIN '
      + 'DROP TABLE Staging_Data.dbo.tbl_tkn_' + CAST(token_schema_details_id as varchar(5)) + ' END '
 +'  CREATE TABLE Staging_Data.dbo.tbl_tkn_' + CAST(token_schema_details_id as varchar(5)) +
 ' ( primary_key_value VARCHAR(50), card_acct_no VARCHAR(100), token_value VARCHAR(100) )'+CHAR(10) AS create_table
 FROM Token_Management.dbo.Token_Schema_Details WITH(NOLOCK)
 
 WHERE  [server] = 'E2PRDDBS01'
 


DECLARE @CodeNameString VARCHAR(max)
SELECT 
   @CodeNameString = STUFF( (SELECT '   ' + createtab 
                             FROM table_list
                             
                             FOR XML PATH('')), 
                            1, 1, '')
                            
select @CodeNameString as create_temptable
 
--EXEC( @CodeNameString) 

No comments:

Post a Comment