Это, кажется, работает нормально для меня.Есть ли у вас триггеры, каскадные внешние ключи и т. Д.?
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