Lahib
Lahib

Reputation: 1365

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. The procedure moves rows from ID< to IDz without any problems. 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 ?

Upvotes: 0

Views: 724

Answers (2)

Praveen Nambiar
Praveen Nambiar

Reputation: 4892

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;

Upvotes: 1

Iswanto San
Iswanto San

Reputation: 18569

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.

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:

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

Upvotes: 2

Related Questions