求高人指点一下这个存储过程哪地方有问题
每次搞存储过程,好多不会,尝试写了一个,运行不太正常,请教问题出在哪。
USE [db]
GO
/****** Object: StoredProcedure [dbo].[XMUserAllot] Script Date: 2013/8/29 23:29:56 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:<Author,,Name>
-- Create date: <Create Date,,>
-- Description:<Description,,>
-- =============================================
ALTER PROCEDURE [dbo].[XMUserAllot]
@UserName varchar(25)
AS
begin
SET NOCOUNT ON;
declare @UserId int,
@ThisUser varchar(25),
@AllotCount smallint,
@RightCount smallint,
@LeftCount smallint
if(@UserName is null)
declare XM_Cursor cursor forward_only static for select [username],[defaultshouquan] from ShouQuanUsers where defaultshouquan>0
else
declare XM_Cursor cursor forward_only static for select [username],[defaultshouquan] from ShouQuanUsers where defaultshouquan>0 and [username]=@UserName
open XM_Cursor
fetch next from XM_Cursor into @ThisUser,@AllotCount
while(@@FETCH_STATUS=0)
begin
select @UserId=[Id] from [User] where UserName=@ThisUser
if(@UserId is not null)
begin
select @RightCount=count(*) from XMUsers where userid=@UserId
set @LeftCount= @AllotCount-@RightCount
if(@LeftCount>0)
update top(@LeftCount) XMUsers set userid=@UserId where userid is null
end
fetch next from XM_Cursor into @ThisUser,@AllotCount
set @UserId=null
end
close XM_Cursor
deallocate XM_Cursor
end
CREATE PROCEDURE [dbo].[XMUserAllot] @UserName VARCHAR(25)
AS
BEGIN
SET NOCOUNT ON;
DECLARE @UserId INT ,
@ThisUser VARCHAR(25) ,
@AllotCount SMALLINT ,
@RightCount SMALLINT ,
@LeftCount SMALLINT
DECLARE XM_Cursor CURSOR forward_only static
FOR
SELECT [username] ,
[defaultshouquan]
FROM ShouQuanUsers
WHERE defaultshouquan > 0
AND (@UserName IS NULL OR [username] = @UserName)--改成这样试试
OPEN XM_Cursor
FETCH NEXT FROM XM_Cursor INTO @ThisUser, @AllotCount
WHILE ( @@FETCH_STATUS = 0 )
BEGIN
SELECT @UserId = [Id]
FROM [User]
WHERE UserName = @ThisUser
IF ( @UserId IS NOT NULL )
BEGIN
SELECT @RightCount = COUNT(*)
FROM XMUsers
WHERE userid = @UserId
SET @LeftCount = @AllotCount - @RightCount
IF ( @LeftCount > 0 )
UPDATE TOP ( @LeftCount )--要保证XMUsers表有足够userid为NULL的记录
XMUsers
SET userid = @UserId
WHERE userid IS NULL
END
FETCH NEXT FROM XM_Cursor INTO @ThisUser, @AllotCount
SET @UserId = NULL
END
CLOSE XM_Cursor
DEALLOCATE XM_Cursor
END