--
=============================================
--
Author: <over>
--
Create date: <2007/09/19>
--
Description: <string.split()拆分字符串>
--
=============================================
ALTER
FUNCTION
[
dbo
]
.
[
Split
]
(
@string
varchar
(
255
),
--
1,2,3,45,
@separator
char
=
'
,
'
)
RETURNS
@temp
TABLE
(
Item
int
)
AS
BEGIN
DECLARE
@Item
int
DECLARE
@CurrentIndex
int
DECLARE
@NextIndex
int
DECLARE
@Length
int
--
字符串的長度
SET
@CurrentIndex
=
1
SET
@Length
=
DATALENGTH
(
@string
)
IF
@string
IS
NOT
NULL
BEGIN
WHILE
@CurrentIndex
<
@Length
BEGIN
--
CHARINDEX(子串,被搜索的字符串)
SET
@NextIndex
=
CHARINDEX
(
@separator
,
@string
,
@CurrentIndex
)
SET
@Item
=
SUBSTRING
(
@string
,
@CurrentIndex
,
@NextIndex
-
@CurrentIndex
)
SET
@CurrentIndex
=
@NextIndex
+
1
--
把臨時變量的值放到要返回的表中
INSERT
INTO
@temp
VALUES
(
@Item
)
END
END
RETURN
END
調用代碼:html
--
=============================================
--
Author: <over>
--
Create date: <2007/09/19>
--
Description: <更新用戶的角色(更改受權)>
--
=============================================
ALTER
PROCEDURE
dbo.UpdUserRole
@UserID
INT
,
--
這裏沒有作UserID的檢查
@RoleIDs
VARCHAR
(
255
)
--
1,2,3,4,5
AS
SET
NOCOUNT
ON
--
單個權限值
DECLARE
@RoleID
INT
--
得到拆分以後的字符串
DECLARE
Roles
CURSOR
FOR
SELECT
Item
FROM
[
dbo
]
.
[
Split
]
(
@RoleIDs
,
default
)
--
for Read Only
--
刪除原有權限
DELETE
FROM
UserRoles
WHERE
UserID
=
@UserID
OPEN
Roles
FETCH
Roles
INTO
@RoleID
WHILE
(
@@FETCH_STATUS
=
0
)
BEGIN
--
SELECT UserID FROM UserRoles WHERE UserID=@UserID AND RoleID=@RoleID
--
if @@rowcount=0
INSERT
INTO
UserRoles
VALUES
(
@UserID
,
@RoleID
)
--
把下一個值塞給變量@RoleID
FETCH
NEXT
FROM
Roles
INTO
@RoleID
END
CLOSE
Roles
--
DEALLOCATE 用於刪除前面準備好的查詢。
--
若是你沒有明確 DEALLOCATE 一個準備好的查詢, 那麼它在會話結束的時候刪除。
DEALLOCATE
Roles
--
RETURN
注意:
此函數在SQLSERVER2005存儲過程當中調用沒有問題,若是須要移植到SQLSERVER2000下,只需把:ide
@separator
char
=
'
,
'
換成
函數
@separator
char
(
1
)
=
'
,
'
可參考曾發過的一篇SQL SERVER2000 存儲過程 設置傳入參數默認值文章。spa