使用 SQL Server 2012。我想将唯一字符串插入表中。我总是想返回唯一字符串的行 ID。现在,这可以通过两种方式实现。
哪种解决方案是最好的?
这是有问题的表格:
CREATE TABLE [dbo].[Comment](
[CommentID] [int] IDENTITY(1,1) NOT NULL,
[Comment] [nvarchar](256) NOT NULL
CONSTRAINT [PK_Comment] PRIMARY KEY CLUSTERED([CommentID] ASC)
)
CREATE UNIQUE NONCLUSTERED INDEX [IX_Comment_Comment] ON [dbo].[Comment]
(
[Comment] ASC
)
解决方案 1:
SELECT
首先检查字符串是否存在。如果是,则返回其ID
. 否则,INSERT
一个新行并返回新创建的ID
.
CREATE PROCEDURE [dbo].[add_comment]
@Comment [nvarchar](256)
AS
BEGIN
SET NOCOUNT ON
DECLARE @CommentID [int]
DECLARE @TransactionCount [int]
BEGIN TRY
SET @TransactionCount = @@TRANCOUNT
IF @TransactionCount = 0
BEGIN TRANSACTION
SELECT @CommentID = [CommentID] FROM [dbo].[Comment] WHERE [Comment] = @Comment
IF @@ROWCOUNT = 0
BEGIN
INSERT INTO [dbo].[Comment]([Comment]) VALUES (@Comment)
SET @CommentID = SCOPE_IDENTITY()
END
IF @TransactionCount = 0
COMMIT TRANSACTION
END TRY
BEGIN CATCH
IF XACT_STATE() <> 0 AND @TransactionCount = 0
ROLLBACK TRANSACTION
; THROW
END CATCH
RETURN @CommentID
END
解决方案 2:
INSERT
第一的。如果插入违反UNIQUE INDEX
,SELECT
则发出 a 。
CREATE PROCEDURE [dbo].[add_comment2]
@Comment [nvarchar](256)
AS
BEGIN
SET NOCOUNT ON
DECLARE @CommentID [int]
BEGIN TRY
INSERT INTO [dbo].[Comment]([Comment]) VALUES (@Comment)
SET @CommentID = SCOPE_IDENTITY()
END TRY
BEGIN CATCH
IF @@ERROR = 2601 -- Duplicate
SELECT @CommentID = [CommentID] FROM [dbo].[Comment] WHERE [Comment] = @Comment
ELSE
THROW
END CATCH
RETURN @CommentID
END
GO
解决方案 3:
想法?:)