I'm trying run this procedure with generic parameters.
If I can't delete because some foreign key, it should update the row.
But when I execute it, still running forever and don't complete the process, any Idea?
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER procedure [dbo].[stp_Batch_Registros_Desativados_Excluir]
@table_name VARCHAR(100),
@id int
AS
BEGIN
DECLARE @column VARCHAR(100),
@sql VARCHAR(300);
SET @column = (SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMNPROPERTY(OBJECT_ID(TABLE_NAME),COLUMN_NAME,'IsIdentity') = 1
AND TABLE_NAME = @table_name);
BEGIN TRY
select @sql = 'DELETE ' + @table_name + ' WHERE ' + @column + ' = ' + CONVERT(VARCHAR,@id);
exec(@sql);
开发者_开发技巧 END TRY
BEGIN CATCH
select @sql = 'UPDATE ' + @table_name + ' SET fg_excluido = 2 WHERE ' + @column + ' = ' + CONVERT(VARCHAR,@id) ;
exec(@sql);
END CATCH;
END
This seems to work fine for me. Do you have triggers, cascading foreign keys, etc.?
USE tempdb;
GO
CREATE TABLE dbo.fooblat1
(
id INT IDENTITY(1,1) PRIMARY KEY,
x VARCHAR(1),
fg_excluido TINYINT NOT NULL DEFAULT 1
);
CREATE TABLE dbo.fooblat2
(
blatid INT NOT NULL FOREIGN KEY REFERENCES dbo.fooblat1(id)
);
INSERT dbo.fooblat1(x) SELECT 'a';
INSERT dbo.fooblat2 SELECT SCOPE_IDENTITY();
INSERT dbo.fooblat1(x) SELECT 'b';
GO
Then:
CREATE PROCEDURE [dbo].[proc]
@table_name VARCHAR(100),
@id INT
AS
BEGIN
SET NOCOUNT ON;
DECLARE @column NVARCHAR(100),
@sql NVARCHAR(MAX);
SELECT @column = name
FROM sys.columns
WHERE [object_id] = OBJECT_ID(@table_name)
AND is_identity = 1;
BEGIN TRY
SET @sql = 'DELETE [' + @table_name
+ '] WHERE [' + @column + '] = '
+ CONVERT(VARCHAR(12),@id);
EXEC sp_executesql @sql;
END TRY
BEGIN CATCH
SET @sql = 'UPDATE [' + @table_name
+ '] SET fg_excluido = 2 WHERE '
+ @column + ' = ' + CONVERT(VARCHAR(12),@id);
EXEC sp_executesql @sql;
END CATCH;
END
GO
Then:
EXEC [dbo].[proc] 'fooblat1', 1; -- should update
GO
EXEC [dbo].[proc] 'fooblat1', 2; -- should delete
GO
SELECT * FROM dbo.fooblat1;
GO
Cleanup:
DROP PROC [dbo].[proc];
DROP TABLE dbo.fooblat2;
DROP TABLE dbo.fooblat1;
GO
精彩评论