SQL儲存過程事務和優化方法(包括查詢方式語句結合)

iSQlServer發表於2009-12-07

CREATE PROCEDURE  IR_rb_User_UpdateUser
(
    @UserID        int,
    @Name    nvarchar(50),
    @Email           nvarchar(100),
    @Password    nvarchar(20),
    @RoleID        int,
    @iSuccess    int output
)
AS

set @iSuccess = -1    --判斷是否成功有錯誤應為插入重複鍵

IF EXISTS (SELECT Email  FROM rb_Users WHERE Email = @Email and UserID<>@UserID)
BEGIN
  set @iSuccess = -2
  return
END

BEGIN TRAN

    UPDATE    rb_Users  SET    Name   = @Name,    Email    = @Email,    Password = @Password  WHERE    UserID   = @UserID

    IF @@ERROR <> 0
    BEGIN
        ROLLBACK TRAN
        return
    END
    set @iSuccess = -3

    update rb_UserRoles set RoleID=@RoleID  where UserID=@UserID

    IF @@ERROR <> 0
    BEGIN
        ROLLBACK TRAN
        return
    END

COMMIT TRAN

set @iSuccess = 1
GO

 

條件查詢語句:

CREATE PROCEDURE IR_SysAuthorization_GetAllSysAuthorization
(
    @Type int,
    @UserID varchar(20)
)
 AS

declare     @strsql    varchar(1500)        --臨時sql語句
declare     @strwhere    varchar(1000)        --臨時sql的條件語句

set @strsql = ''
set @strsql = @strsql + 'select UserID,Role,(select typename from SysAuthorizationType where type=t.type) as typeTmp, '
set @strsql = @strsql + '(CASE WHEN State = 1 THEN ' + '''有效''' + ' ELSE ' + '''無效''' + ' END) AS StateTmp '
set @strsql = @strsql + 'FROM SysAuthorization t '

set @strwhere = ''


IF  @UserID <> ''
BEGIN
    set @strwhere = @strwhere + ' and (UserID LIKE ' + '''' + '%' + @UserID + '%' + '''' + ')'
END

IF  @Type >0
BEGIN
    set @strwhere = @strwhere + ' and Type =  ' + CAST(@Type AS varchar(12))
END

if @strwhere <>''
BEGIN
    set @strsql = @strsql + ' where ' + right(@strwhere, len(@strwhere)-4)
END

--按使用者名稱排序
set  @strsql = @strsql + ' ORDER BY Type,UserID'

exec (@strsql)
GO

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/16436858/viewspace-621846/,如需轉載,請註明出處,否則將追究法律責任。

相關文章