在做数据库系统开发时,特别是需要对数据库操作进行性能测试及优化时,我们就需要在数据库测试表中插入大量数据以便测试。对于这些数据的插入,这里通过实例展示如何通过存储过程进行实现。
数据库表(userInfo)结构如下:
CREATE
TABLE
[
dbo
]
.
[
userInfo
]
(
[
userID
]
[
int
]
IDENTITY
(
1
,
1
)
NOT
NULL
,
[
roleType
]
[
int
]
NULL
,
[
groupID
]
[
int
]
NULL
,
[
userCode
]
[
varchar
]
(
50
)COLLATEChinese_PRC_CI_AS
NULL
,
[
userName
]
[
varchar
]
(
50
)COLLATEChinese_PRC_CI_AS
NULL
,
[
text1
]
[
varchar
]
(
50
)COLLATEChinese_PRC_CI_AS
NULL
,
[
text2
]
[
varchar
]
(
50
)COLLATEChinese_PRC_CI_AS
NULL
,
[
text3
]
[
varchar
]
(
50
)COLLATEChinese_PRC_CI_AS
NULL
)
ON
[
PRIMARY
]
GO
存储过程如下(这里是批量插入99000条数据,roleType,groupID两个字段为随机生成的0-5之间的数):
CREATE
PROCEDURE
add_UserInfo
AS
DECLARE
@userCode
VARCHAR
(
30
)
DECLARE
@userName
VARCHAR
(
30
)
DECLARE
@userCode_base
VARCHAR
(
30
)
DECLARE
@count
INTEGER
DECLARE
@index
INTEGER
DECLARE
@rand1
INTEGER
DECLARE
@rand2
INTEGER
SET
@userCode_base
=
'
qs_
'
SET
@userName
=
'
userName
'
SET
@count
=
100000
SET
@index
=
10000

WHILE
@index
<
@count
BEGIN
SET
@userCode
=
@userCode_base
+
CONVERT
(
VARCHAR
,
@index
)
SET
@rand1
=
convert
(
int
,
rand
()
*
5
)
SET
@rand2
=
convert
(
int
,
rand
()
*
5
)
INSERT
INTO
userInfo(userCode,roleType,groupID,userName,text1,text2,text3)
VALUES
(
@userCode
,
@rand1
,
@rand2
,
@userName
,
'
aokeikaoljof
'
,
''
,
'
aokeikaoljof
'
)
SET
@index
=
@index
+
1
END
GO
转自: http://blog.youkuaiyun.com/qinysong/archive/2006/07/27/982662.aspx
本文介绍了一种通过存储过程在SQL Server中批量插入数据的方法。以userInfo表为例,展示了如何使用存储过程生成99000条记录,包括随机生成部分字段值的过程。
4167

被折叠的 条评论
为什么被折叠?



