我在SQL Server中创建了下表
CREATE TABLE [dbo].[SimpleTable](
[ID] [int] IDENTITY(1,1) NOT NULL,
[Name] [varchar](50) NOT NULL,
[OtherField] [varchar](50) NOT NULL,
[Position] [int] NULL,
CONSTRAINT [PK_SimpleTable] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
当插入新记录时,我想用IDENTITY列中的值更新Position字段,主要思想是记录应该放在最后,但用户稍后可以更改该位置
我考虑过在插入后创建一个触发器并更新位置字段,但是我会有很多这些表,如果可以的话,我真的想尽量远离触发器。
有没有人有更优雅的解决方案?
答案 0 :(得分:1)
这应该在存储过程中起作用。
CREATE PROCEDURE [dbo].[InsertIntoSimpleTable]
@Name varchar(50)
, @OtherField varchar(50)
AS
BEGIN
DECLARE @Id INT;
--- Do your insert here.
INSERT INTO SimpleTable (Name, OtherField)
SELECT @Name, @OtherField
;
SELECT @Id = SCOPE_IDENTITY();
UPDATE SimpleTable SET Position = @Id WHERE Id = @Id;
END
答案 1 :(得分:0)
触发器并不坏。 Greco的解决方案很好但是我发布了一个触发器解决方案,以防你没有通过程序向表中插入数据
create trigger TR_SetDefaultValue
on [SimpleTable]
after insert
as
begin
UPDATE [SimpleTable]
SET [Position] = I.[ID]
FROM INSERTED AS I
WHERE [SimpleTable].ID=I.ID
end