如果您的应用程序中有一个 DataTable,并且这是 1000 个名称的来源,您可以为此使用表值参数。
首先,一个表类型:
CREATE TYPE dbo.Names AS TABLE
(
Name NVARCHAR(255),
email VARCHAR(320),
[password] VARBINARY(32) -- surely you are not storing this as a string!?
);
然后是使用它的过程:
CREATE PROCEDURE dbo.Names_BulkInsert
@Names dbo.Names READONLY
AS
BEGIN
SET NOCOUNT ON;
INSERT dbo.RealTable(Name, email, password)
SELECT Name, email, password
FROM @Names;
END
GO
然后你的 C# 代码可以说:
SqlCommand cmd = new SqlCommand("dbo.Names_BulkInsert", connection_object);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter names = cmd.Parameters.AddWithValue("@Names", DataTableName);
names.SqlDbType = SqlDbType.Structured;
cmd.ExecuteNonQuery();
如果您只想生成 1000 行随机值:
;WITH x AS
(
SELECT TOP (1000) n = REPLACE(LEFT(name,32),'_','')
FROM sys.all_columns ORDER BY NEWID()
)
-- INSERT dbo.sometable(name, email, [password])
SELECT
name = LEFT(n,3),
email = RIGHT(n,5) + '@' + LEFT(n,2) + '.com',
[password] = CONVERT(VARBINARY(32), SUBSTRING(n, 1, 32))
FROM x;
在这两种情况下,您都不应该使用 while 循环或游标。恕我直言。