gpt4 book ai didi

sql-server-2008 - 快速更新插入 Sql server 2008 R2

转载 作者:行者123 更新时间:2023-12-03 14:52:21 26 4
gpt4 key购买 nike

我正在尝试使用 SP 将记录更新插入一张表中。

CREATE TABLE [dbo].[SHARE_AD_GROUP](
[SHARE_AD_GROUP_ID] [int] IDENTITY(1,1) NOT NULL,
[SHARE_ID] [int] NOT NULL,
[AD_GROUP] [varchar](200) NOT NULL,
[SHARE_PERMISSIONS] [varchar](65) NULL,

以下哪种方法最好:

1-
ALTER PROCEDURE [dbo].[PROC_INSERT_SHARE_AD_GROUP]


@shareID int,
@ownerId varchar(200),
@sharePermissions varchar(65)

AS

BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;

UPDATE [dbo].SHARE_AD_GROUP
SET
[SHARE_PERMISSIONS] = @sharePermissions
WHERE SHARE_ID = @shareID and [AD_GROUP] = @ownerId
if @@ROWCOUNT =0
begin
INSERT INTO [dbo].SHARE_AD_GROUP
(SHARE_ID,[AD_GROUP],[SHARE_PERMISSIONS])
VALUES
(@shareID,@ownerId,@sharePermissions)
end

end

2-
   BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.

declare @id int
SET NOCOUNT ON;
set @id = (select top 1 SHARE_AD_GROUP_ID from SHARE_AD_GROUP where SHARE_ID = @shareID and [AD_GROUP] = @ownerId)
if @id is null
begin
INSERT INTO [dbo].SHARE_AD_GROUP
(SHARE_ID,[AD_GROUP],[SHARE_PERMISSIONS])
VALUES
(@shareID,@ownerId,@sharePermissions)
set @id = SCOPE_IDENTITY()
end
else
begin
UPDATE [dbo].SHARE_AD_GROUP
SET
[SHARE_PERMISSIONS] = @sharePermissions
WHERE SHARE_ID = @shareID and [AD_GROUP] = @ownerId
end
End

3- 合并 ==> 不知道怎么写。

你认为最快的方法是什么?

最佳答案

我认为合并语句比您以两种方式展示的更快。如果您需要了解有关如何在 sql server 中编写 MERGE INTO Query 的更多信息,请点击链接。

http://blog.sqlauthority.com/2008/08/28/sql-server-2008-introduction-to-merge-statement-one-statement-for-insert-update-delete/

https://www.simple-talk.com/sql/learn-sql-server/the-merge-statement-in-sql-server-2008/

你的合并块看起来像这样,你需要把它放在你的存储过程或任何其他地方。

MERGE INTO SHARE_AD_GROUP A
USING (
SELECT SHARE_AD_GROUP_ID,
SHARE_ID,
AD_GROUP,
SHARE_PERMISSIONS
FROM SHARE_AD_GROUP
WHERE SHARE_ID = @shareID AND AD_GROUP = @ownerId
) B ON (A.SHARE_AD_GROUP_ID = B.SHARE_AD_GROUP_ID)
WHEN MATCHED THEN
UPDATE SET A.SHARE_PERMISSIONS = B.SHARE_PERMISSIONS
WHEN NOT MATCHED THEN
INSERT (SHARE_PERMISSIONS) VALUES(@sharePermissions);

关于sql-server-2008 - 快速更新插入 Sql server 2008 R2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18873747/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com