我正在尝试使用通用参数运行此过程。
如果由于某些外键而无法删除,则应更新该行。
但是当我执行它,仍然永远运行并且没有完成这个过程时,任何想法?
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
答案 0 :(得分:0)
这对我来说似乎很好。你有触发器,级联外键等吗?
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
然后:
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
然后:
EXEC [dbo].[proc] 'fooblat1', 1; -- should update
GO
EXEC [dbo].[proc] 'fooblat1', 2; -- should delete
GO
SELECT * FROM dbo.fooblat1;
GO
清理:
DROP PROC [dbo].[proc];
DROP TABLE dbo.fooblat2;
DROP TABLE dbo.fooblat1;
GO