Tuesday, 25 August 2015

script to create store procedure disable row by giving table name in sql server

alter PROC [dbo].[GENERATEQUERYDel]
@TBL VARCHAR(50)=''
AS
BEGIN
DECLARE @CR  VARCHAR(200)='';
select @CR +='CREATE PROCEDURE '+TABLE_SCHEMA+'.Pr'+upper(left(@TBL,1))+right(@TBL,len(@TBL)-1)+'Del'
from INFORMATION_SCHEMA.TABLES
where TABLE_NAME=@TBL

declare @schema varchar(10);
select @schema =TABLE_SCHEMA
from INFORMATION_SCHEMA.TABLES
where TABLE_NAME=@TBL

declare @db varchar(10);
select @db =TABLE_CATALOG
from INFORMATION_SCHEMA.TABLES
where TABLE_NAME=@TBL


declare @par nvarchar(1000)='';
select @par+='@'+COLUMN_NAME+' '+DATA_TYPE +case
    when CHARACTER_MAXIMUM_LENGTH is null
    then ''
    when CHARACTER_MAXIMUM_LENGTH is not null
    then '('+CAST( REPLACE(CHARACTER_MAXIMUM_LENGTH,'-1','max') as varchar)+')'
    end +CHAR(10)
from INFORMATION_SCHEMA.COLUMNS cl
join sys.columns C
    on c.is_identity=1 and Cl.TABLE_NAME=OBJECT_NAME(object_id) and cl.COLUMN_NAME=c.name
where cl.TABLE_NAME= @TBL
       

declare @beb varchar(200) ='AS' +CHAR(10) +'BEGIN'+CHAR(10)+'SET ANSI_NULLS ON;'+CHAR(10)+'SET QUOTED_IDENTIFIER ON;'+CHAR(10)+'SET NOCOUNT ON;'+CHAR(10)+CHAR(10);
SET @beb+='BEGIN TRAN'+CHAR(10);
SET @beb+='BEGIN TRY'+CHAR(10) +CHAR(10);

-- Delete start

declare @update varchar(1000) ='UPDATE '+@schema+'.'+@TBL+' SET CurrentStatus=''D''';


declare @identityCol varchar(50)='';
select @identityCol=COLUMN_NAME
from INFORMATION_SCHEMA.COLUMNS cl
join sys.columns C
    on c.is_identity=1 and Cl.TABLE_NAME=OBJECT_NAME(object_id) and cl.COLUMN_NAME=c.name
where cl.TABLE_NAME= @TBL;

if(len(@identityCol) > 1)
begin
set @update +=' WHERE ';

set @update+=@identityCol+'=@'+@identityCol;

end

-- Delete end

DECLARE @END VARCHAR(50) =CHAR(10)+'COMMIT TRAN'+CHAR(10)+'END TRY'+CHAR(10);
DECLARE @CATCH VARCHAR(500) ='BEGIN CATCH'+CHAR(10)+'ROLLBACK TRAN'+CHAR(10)+CHAR(10)+CHAR(5)+CHAR(5)+CHAR(5)+'INSERT INTO ADMIN.TBLERRORlOG (CustomeError) VALUES (NULL);'+CHAR(10)+CHAR(10)+'END CATCH'+CHAR(10)+'END';

declare @h bit=0;

if exists (select 1 from INFORMATION_SCHEMA.COLUMNS where COLUMN_NAME='CurrentStatus' and TABLE_NAME=@tbl )
if( len(@par) > 1 )
begin

print @CR+CHAR(10)+@par+CHAR(10)+@beb+CHAR(10)+@update+CHAR(10)+@END+CHAR(10)+@CATCH+char(10)+'Go';

end

END

No comments:

Post a Comment