I have tried to write a script that will generate select script for a table .Sometimes it is very difficult for us to write all columns name in select query.To write all fields is easy task because we can write SELECT *. But suppose i want select 99 columns from 100.
T-SQL:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/*
Objective :Generate Select script for table
Version :Beta Version 1.0
Developed By :Shatrughna Kumar
Last Modified Date:23rd-Apr-2012
*/
CREATE PROCEDURE [dbo].[spGenenrateSelectScript]
(
@TABLENAME VARCHAR(200)
)
AS
BEGIN
DECLARE @COLUMNLISTS VARCHAR(MAX)
DECLARE @SELQUERY VARCHAR(MAX)
DECLARE @ISTABLENAME VARCHAR(200)
SET @ISTABLENAME = REPLACE(@TABLENAME,'dbo.','')
SELECT @COLUMNLISTS =
STUFF((SELECT ','+COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS
WHERE
TABLE_NAME = @ISTABLENAME
FOR XML PATH('')),1,1,'')
SET @SELQUERY = 'SELECT '+@COLUMNLISTS + ' FROM '+ @TABLENAME
PRINT @SELQUERY
END
That’s It.
Enjoy Learning.
No comments:
Post a Comment