MSSQL-server存储过程仅插入最后一行

时间:2013-03-04 08:29:16

标签: sql sql-server stored-procedures

我创建了一个存储过程来将所有项目从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;

有人可以帮忙吗?

2 个答案:

答案 0 :(得分:1)

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

当您使用变量并使用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

答案 1 :(得分:1)

  

一旦声明了这样的变量,你就无法批量插入值。   简单的方法是这样做:

INSERT INTO dbo.AliasMoveLog (CustID, Alias, Username)
SELECT CustID, Alias, @Username FROM dbo.Alias WHERE AdrID = @SourceAdrID;