0

我创建了一个存储过程来将所有项目从 IDx 移动到 IDz,并且它必须记录它移动的每一行的一些数据。该过程将行从 ID< 移动到 IDz 没有任何问题。但是当它必须记录信息时,它只记录移动的最后一行。我究竟做错了什么?

这是我的代码:

USE [TrackIT_Test]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[MoveCustIDAndAlias] 
    -- Add the parameters for the stored procedure here
    @SourceAdrID int,
    @TargetAdrID int,
    @Username varchar(50)
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    declare @custID varchar(50)
    set @custID = ''

    declare @alias varchar(50)
    set @alias = ''

    -- Insert statements for procedure here
    Select @custID = (CustID), @alias = (Alias) from dbo.Alias where AdrID = @SourceAdrID;
    Insert into dbo.AliasMoveLog (CustID, Alias, Username) VALUES (@custID, @alias, @Username);
    UPDATE dbo.Alias SET AdrID = @TargetAdrID WHERE  AdrID = @SourceAdrID;

任何人都可以帮忙吗?

4

2 回答 2

2

是的,我看到了你的问题。

当您使用变量并使用 select 设置变量值时,它将仅存储最后一行中的值。

你可以试试这个来证明:

CREATE TABLE tbl
(
    col1 INT
);
INSERT INTO tbl VALUES (1);
INSERT INTO tbl VALUES (2);
INSERT INTO tbl VALUES (3);

DECLARE @x int
SELECT @x = col1 FROM tbl
PRINT @x -- will print 3

对于您的 sp,请尝试更改此行:

Select @custID = (CustID), @alias = (Alias) from dbo.Alias where AdrID = @SourceAdrID;
Insert into dbo.AliasMoveLog (CustID, Alias, Username) VALUES (@custID, @alias, @Username);

到:

Insert into dbo.AliasMoveLog (CustID, Alias, Username)
Select CustID, Alias, @Username from dbo.Alias where AdrID = @SourceAdrID;

更多细节:SELECT @local_variable

于 2013-03-04T08:35:33.233 回答
1

好吧,一旦您声明了这样的变量,您就不能批量插入值。简单的方法是这样做:

INSERT INTO dbo.AliasMoveLog (CustID, Alias, Username)
SELECT CustID, Alias, @Username FROM dbo.Alias WHERE AdrID = @SourceAdrID;
于 2013-03-04T08:53:56.340 回答