如何从C#中的SQL Server存储过程中传递datatable作为参数

问题描述:

USE [callService]
GO

/****** Object:  UserDefinedTableType [dbo].[code_front]    Script Date: 10/24/2016 14:25:30 ******/
CREATE TYPE [dbo].[code_front] AS TABLE(
	[createdonUTC] [datetime] NOT NULL,
	[createdTimezone] [int] NOT NULL,
	[phaseCount] [nvarchar](2) NOT NULL
)
GO



这是在sql server 2008 r2中创建的用户定义表。



现在我将一个相同的数据表从c#传递给过程。





名为code_master的sql server表,其列为


This is user defined table created in sql server 2008 r2.

Now I'm passing a same datatable from c# to procedure.


sql server table named "code_master" having the columns are

code,createdonUTC,createdTimezone,phaseCount



其中代码为nvarchar(50)和主键。





现在向code_master输入数据的过程---------


where code in nvarchar(50) and primary key.


Now the procedure to enter data to code_master---------

USE [callService]
GO
/****** Object:  StoredProcedure [dbo].[Insert_Code]    Script Date: 10/24/2016 13:51:41 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[Insert_Code]
      @tblcode code_front READONLY
AS
BEGIN
      SET NOCOUNT ON;
     
      INSERT INTO code_master(code,createdonUTC,createdTimezone,phaseCount) output 1
      SELECT cast((convert(numeric(16,0),rand() * 8999999999999999) + 1000000000000000) as nvarchar) as code,
      createdonUTC,createdTimezone,phaseCount
      from @tblcode
END





我知道错误在SELECT cast((转换(数字) (16,0),rand()* 8999999999999999)+ 1000000 000000000)作为nvarchar)代码 - 因为用户定义的表中没有列代码。



但是我希望你明白我在想什么实现。

我会将批量数据从c#传递到sql用户表,该表将为每一行生成随机数,然后所有带有随机数的数据将作为列插入到code_master表中代码是随机数。



请帮助我如何实现。在程序方式或其他方式。

但我不想在c#本身生成随机数,因为我担心对于该应用程序的每次运行,随机数可能会重复,因为我无法保存以前数字。

但是在sql中,它不会生成相同的数字(至少对于许多组合,因为我创建了16位数,这将产生许多crores数字)。



我尝试过:



上面写的。程序和表。



I know the mistake is in "SELECT cast((convert(numeric(16,0),rand() * 8999999999999999) + 1000000000000000) as nvarchar) as code"- as there is no column "code" in the user defined table.

But I hope you understand what I'm trying to achieve.
I'll pass bulk data from c# to a sql user table,the table will generate random numbers for each row and then all the data with random number will be inserted to code_master table as the column "code" is for the random number.

Please help me how to achieve. On the procedure way or another way.
But I don't want to generate random number in c# itself because I fear that for every run of that application random number may repeat as nowhere I'm saving previous numbers.
But in sql, it doesn't generate same number (at least for many combination as I created 16 digit which will make many crores numbers).

What I have tried:

Written above. The procedure and the tables.

具体问题,下面的帖子将帮助你

请参考将(传递)DataTable作为参数发送到C#中的存储过程和VB.Net [ ^ ]
Be specific about the problem, below post will help you
Please refer Send (Pass) DataTable as parameter to Stored Procedure in C# and VB.Net[^]