Groups | Blog | Home
all groups > sql server (microsoft) > march 2005 >

sql server (microsoft) : Moving data between tables


Jason Williard
3/20/2005 7:19:36 PM
I am currently using a stored procedure to delete users from our database
who are considered inactive. This works great. However, we have decided
that we want to archive these users to a identical (structure) table in the
same database. To do this, I need to find an easy way to take the data from
one table and move it to the other table using a stored procedure. I can't
think of an easy way to do this. Is it possible and if so, can anyone help
me set this up?

Here is our current stored proc:
---
CREATE PROCEDURE dbo.CleanDB (@rowcount int OUTPUT)
AS

SET NOCOUNT ON
DECLARE @error int

SELECT *
FROM dbo.users
WHERE (userJoinDate < GETDATE() - 30)
AND (userExpirationDate IS NULL)
AND (userLastPaidDate IS NULL)

SELECT @error = @@ERROR, @rowcount = @@ROWCOUNT

IF @error <> 0 BEGIN
RETURN 0
END

RETURN 1
GO
---


Thank You,
Jason Williard

Walter Clayton
3/21/2005 12:18:03 AM
This proc simply returns a row count without actually deleting.

Assuming that's a simple over sight and making an assumption about what it
really looks like...

CREATE PROCEDURE dbo.CleanDB (@rowcount int OUTPUT)
AS

SET NOCOUNT ON
DECLARE @error int

insert into dbo.users_archive
select *
from dbo.users
where (userJoinDate < getdate() - 30)
and (userExpirationData is NULL)
and (userLastPaidDate is NULL)
;

select @error = @@error, @rowcount = -1
if @@error = 0 begin
delete
from dbo.users
where (userJoinDate < getdate() - 30)
and (userExpirationData is NULL)
and (userLastPaidDate is NULL)
select @error = @@error, @rowcount = @@rowcount
;
end

/* Are you sure about this logic? Return 0 if there was an error, else 1? */

IF @error <> 0 BEGIN
RETURN 0
END

RETURN 1
GO

--
Walter Clayton
Any technology distinguishable from magic is insufficiently advanced.


[quoted text, click to view]
Ray
3/22/2005 12:19:04 PM
You'll probably want to add some transaction code to avoid any chance of
data loss.

CREATE PROCEDURE dbo.CleanDB (@rowcount int OUTPUT)
AS

SET NOCOUNT ON
DECLARE @error int

Begin Tran

insert into dbo.users_archive
select *
from dbo.users
where (userJoinDate < getdate() - 30)
and (userExpirationData is NULL)
and (userLastPaidDate is NULL)
;

select @error = @@error

Delete
from dbo.users
where (userJoinDate < getdate() - 30)
and (userExpirationData is NULL)
and (userLastPaidDate is NULL)
select @error = @@error
;

IF @error = 0
BEGIN
COMMIT
RETURN 0
END
ELSE
BEGING
ROLLBACK
RETURN 1
END
GO

[quoted text, click to view]

bb_43 NO[at]SPAM hotmail.com
3/22/2005 3:27:19 PM
[quoted text, click to view]

AddThis Social Bookmark Button