简体   繁体   English

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

[英]MSSQL-server Stored procedure inserting only last Row

I have created a stored procedure to Move all items from IDx to IDz and as it does that it has to log some data of each row it moves. 我创建了一个存储过程来将所有项目从IDx移动到IDz,并且它必须记录它移动的每一行的一些数据。 The procedure moves rows from ID< to IDz without any problems. 该过程将行从ID <移动到IDz而没有任何问题。 But when it has to log the information it only logs the last row that is moved. 但是当它必须记录信息时,它只记录移动的最后一行。 What am i doing wrong? 我究竟做错了什么?

this is my code: 这是我的代码:

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;

Can anyone help ? 有人可以帮忙吗?

Yes, I see your problem. 是的,我看到了你的问题。

When you're using variable and set the variable value with select, it will store only the value in the last row. 当您使用变量并使用select设置变量值时,它将仅存储最后一行中的值。

You can try this to prove it: 你可以试试这个证明:

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

For your sp, try to change this line: 对于你的sp,尝试更改此行:

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

to: 至:

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

More detail: SELECT @local_variable 更多细节: SELECT @local_variable

Well you cannot bulk insert values once you declare the variable like that. 一旦你声明了这样的变量,你就不能批量插入值。 Simple way is to do it this way: 简单的方法是这样做:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM