I am trying to display my data table with a grid view
protected void show_data(object sender, EventArgs e)
{
string str = "Data Source=(LocalDB)\\MSSQLLocalDB;";
str += "AttachDbFilename=|DataDirectory|DinoData.mdf;";
str += "Integrated Security= True";
SqlConnection c;
c = new SqlConnection(str);
GV.DataSource = User;
GV.DataBind();
}
the error:
An exception of type 'System.InvalidOperationException' occurred in
System.Web.dll but was not handled in user code
Additional information: Data source is an invalid type. It must be
either an IListSource, IEnumerable, or IDataSource.
user table:
CREATE TABLE [dbo].[User] (
[Username] VARCHAR (100) NOT NULL,
[Pasword] VARCHAR (100) NOT NULL,
[FName] VARCHAR (MAX) NOT NULL,
[LName] VARCHAR (MAX) NOT NULL,
[Location] VARCHAR (MAX) NOT NULL,
[Profesion] VARCHAR (MAX) NOT NULL,
[email] VARCHAR (MAX) NOT NULL,
[gender] VARCHAR (MAX) NOT NULL,
[money] INT NOT NULL,
[property] VARCHAR (MAX) NULL,
[xp] INT NOT NULL,
[level] INT NOT NULL,
PRIMARY KEY CLUSTERED ([Username] ASC)
);
What should i do?
If I want to show only part of the table with gridview how to do it?
You have no query to select rows from your database ,you must have a selection statment like :
protected void show_data(object sender, EventArgs e)
{
string str = "Data Source=(LocalDB)\\MSSQLLocalDB;";
str += "AttachDbFilename=|DataDirectory|DinoData.mdf;";
str += "Integrated Security= True";
SqlConnection c;
c = new SqlConnection(str);
DataTable dt = new DataTable();
//For exemple t select all rows in you Table User,you can insert a condition here
String req = "SELECT * FROM [User]";
SqlDataAdapter da = new SqlDataAdapter(req, c);
da.Fill(dt);
GV.DataSource = dt;
GV.DataBind();
}
Related
I am trying to create a generic module that will load .csv files into SQL tables. The SQL tables are already created and their names, and the name of the file, will be passed as parameters. This what I have so far...
public void Main()
{
var mFilepath = Dts.Variables["InputFile"].Value.ToString();
var mSQLTable = "[Staging].[tblLoadBUF]";
Dts.Variables["StagingTableGetColumnsScript"].Value =
"IF EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'tblLoadBUF') " +
"BEGIN; " +
"SELECT COLUMN_NAME " +
"FROM INFORMATION_SCHEMA.COLUMNS " +
"WHERE TABLE_NAME = 'tblLoadBUF'; " +
"END; ";
string connectionString = Dts.Connections["OLEDB_CONN"].ConnectionString;
connectionString = connectionString.Trim(';');
var connStrDictionary = connectionString.Split(';').Select(x => x.Split('=')).ToDictionary(x => x[0], x => x[1]);
connectionString = "Data Source=" + connStrDictionary["Data Source"] + ";Initial Catalog=" + connStrDictionary["Initial Catalog"] + ";Integrated Security=" + connStrDictionary["Integrated Security"];
try
{
DataTable dt = new DataTable();
string contents = File.ReadAllText(mFilepath, System.Text.Encoding.GetEncoding(1252));
TextFieldParser parser = new TextFieldParser(new StringReader(contents));
parser.HasFieldsEnclosedInQuotes = true;
parser.SetDelimiters(",");
string[] fields;
while (!parser.EndOfData)
{
fields = parser.ReadFields();
if (dt.Columns.Count == 0)
{
foreach (string field in fields)
{
dt.Columns.Add(new DataColumn(string.IsNullOrWhiteSpace(field.Trim('\"')) ? null : field.Trim('\"'), typeof(string)));
}
}
else
{
dt.Rows.Add(fields.Select(item => string.IsNullOrWhiteSpace(item.Trim('\"')) ? null : item.Trim('\"')).ToArray());
}
}
parser.Close();
var columnNames = new List<string>();
using (var cn = new SqlConnection() { ConnectionString = connectionString })
{
using (var cmd = new SqlCommand() { Connection = cn })
{
cmd.CommandText = Dts.Variables["StagingTableGetColumnsScript"].Value.ToString();
cn.Open();
var reader = cmd.ExecuteReader();
while (reader.Read())
{
columnNames.Add(reader.GetString(0));
}
cn.Close();
}
}
using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(con))
{
sqlBulkCopy.DestinationTableName = mSQLTable;
sqlBulkCopy.ColumnMappings.Clear();
con.Open();
foreach (var column in columnNames)
{
sqlBulkCopy.ColumnMappings.Add(column.ToString(), column.ToString());
}
sqlBulkCopy.WriteToServer(dt);
con.Close();
}
}
Dts.TaskResult = (int)ScriptResults.Success;
}
catch (Exception ex)
{
Dts.Events.FireError(0, "Something went wrong ", ex.ToString(), string.Empty, 0);
Dts.TaskResult = (int)ScriptResults.Failure;
}
}
I get the following error message at execution:
System.InvalidOperationException: The given value of type String from the data source cannot be converted to type bit of the specified target column. ---> System.FormatException: Failed to convert parameter value from a String to a Boolean. ---> System.FormatException: String was not recognized as a valid Boolean.
Can somebody help me fix this ? I understand the error message, but I find it strange that it doesn't complain about decimal or integer values.
Here is my SQL Table:
CREATE TABLE [Staging].[tblLoadBUF](
[Bg_SN] [NVARCHAR](12) NOT NULL,
[Bg_Type] [NVARCHAR](7) NOT NULL,
[Bg_Expected_BUs] [NUMERIC](4, 0) NOT NULL,
[Bg_Validity_Likelihood] [DECIMAL](5, 4) NOT NULL,
[Bg_Mixed_Usage] [NUMERIC](1, 0) NOT NULL,
[Bg_Status] [NVARCHAR](1) NOT NULL,
[BU_SN] [NVARCHAR](12) NOT NULL,
[BU_Residential_Occup_Likelihood] [DECIMAL](5, 4) NOT NULL,
[BU_Last_Res_Confirmation] [DATE] NULL,
[BU_Last_NRes_Usage] [NVARCHAR](7) NULL,
[BU_Last_NRes_Confirmation] [DATE] NULL,
[BU_Validity_Likelihood] [DECIMAL](5, 4) NOT NULL,
[BU_Status] [NVARCHAR](1) NOT NULL,
[BU_Mailing_Address_Availability] [NUMERIC](1, 0) NOT NULL,
[BU_Mailing_Address_Likelihood] [DECIMAL](5, 4) NULL,
[BU_Usage] [NUMERIC](1, 0) NOT NULL,
[BU_Co_SN] [NVARCHAR](12) NULL,
[Co_Type] [NVARCHAR](5) NULL,
[Co_Validity_Likelihood] [DECIMAL](5, 4) NULL,
[Co_Status] [NVARCHAR](1) NULL,
[TN_LTotal] [INT] NOT NULL,
[TN_CTotal] [INT] NOT NULL,
[TN_OTotal] [INT] NOT NULL,
[TN_Total] [INT] NOT NULL,
[EA_Total] [INT] NOT NULL,
[BB_UID] [NUMERIC](10, 0) NULL,
[BB_BPIR] [NVARCHAR](4) NOT NULL,
[CUID] [NVARCHAR](8) NULL,
[COLB] [NVARCHAR](10) NULL,
[DAID] [NVARCHAR](8) NULL,
[DISB] [NVARCHAR](11) NULL,
[CSD_Name] [NVARCHAR](100) NULL,
[CSD_UID] [NVARCHAR](7) NULL,
[CSD_Type] [NVARCHAR](3) NULL,
[SAC_Code] [NVARCHAR](3) NULL,
[PC_CUID] [NVARCHAR](8) NULL,
[PC_DAID] [NVARCHAR](8) NULL,
[PC_CSD_UID] [NVARCHAR](7) NULL,
[PC_CSD_Type] [NVARCHAR](3) NULL,
[PC_SAC_Code] [NVARCHAR](3) NULL,
[LFS_UID] [NVARCHAR](13) NULL,
[ER_UID] [NVARCHAR](4) NULL,
[HR_UID] [NVARCHAR](4) NULL,
[PRCODE] [NVARCHAR](2) NOT NULL,
[BU_CPC_Postal_Code] [NVARCHAR](6) NULL,
[Bg_Latitude] [DECIMAL](9, 6) NULL,
[Bg_Longitude] [DECIMAL](11, 6) NULL,
[Bg_Coordinate_Type] [NVARCHAR](1) NOT NULL,
[AR_UID] [NVARCHAR](10) NULL,
[Frame_ID] [NVARCHAR](8) NULL,
[Do_Not_Contact_Flag] [BIT] NULL,
PRIMARY KEY CLUSTERED
(
[BU_SN] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
And my .csv file contains values of 1 and 0 in column [Do_Not_Contact_Flag].
Pease note that English is not my primary language, so just let me know if this is not clear enough. And thanks in advance for you help :-)
Mylene
I found the solution !!
I've modified my staging table column [Do_Not_Contact_Flag] to be SMALLINT, and added the conversion to BIT in my processing stored proc before loading in the final SQL Table.
I am trying to insert data into a SQL Server table, but it is not allowing me to do so and throws an error. I think the error is from the role I don't know how to fix it; please I need your help - thank you.
This is the member table that I am using:
CREATE TABLE [dbo].[Member]
(
[Member_Username] NVARCHAR (50) NOT NULL,
[Password] NVARCHAR (25) NOT NULL,
[Role] NVARCHAR (10) NULL,
[FirstName] NVARCHAR (50) NOT NULL,
[LastName] NVARCHAR (50) NOT NULL,
[Gender] NVARCHAR (8) NOT NULL,
[Email] NVARCHAR (50) NULL,
[DateOfBirth] DATE NOT NULL,
PRIMARY KEY CLUSTERED ([Member_Username] ASC)
);
And this is the error I get when inserting the values into the table:
System.Data.SqlClient.SqlException:
The parameterized query '(#memberU nvarchar(1), #pwd nvarchar(1), #role nvarchar(4000), #fna' expects the parameter '#role', which was not supplied.
This is the member class that I have for inserting the user in the database table:
public void AddMember()
{
// Open database connection
SqlConnection conn = new SqlConnection();
conn.ConnectionString = Config.GetConnectionStr();
conn.Open();
// Prepare SQL command with parameters
string sql = "INSERT INTO Member VALUES (#memberU, #pwd, #role, #fname, #lname, #gender, #email, #dob)";
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("memberU", this.Member_Username);
cmd.Parameters.AddWithValue("pwd", this.Password);
cmd.Parameters.AddWithValue("role", this.Role);
cmd.Parameters.AddWithValue("fname", this.FirstName);
cmd.Parameters.AddWithValue("lname", this.LastName);
cmd.Parameters.AddWithValue("email", this.Email);
// handling null values for gender and date of birth column
if (this.Gender != null)
{
cmd.Parameters.AddWithValue("gender", this.Gender);
}
else
{
cmd.Parameters.AddWithValue("gender", DBNull.Value);
}
if (this.DateofBirth != null)
{
cmd.Parameters.AddWithValue("dob", this.DateofBirth);
}
else
{
cmd.Parameters.AddWithValue("dob", DBNull.Value);
}
// Execute command
cmd.ExecuteNonQuery();
}
And this is the sign up button:
protected void btnSignUp_Click(object sender, EventArgs e)
{
if (Page.IsValid)// assuming you have done validations using validation controls
{// c create a new object of type member and set all it's properties to values from controls
Members user = new Members();
//reading required values
user.FirstName = txtFirstName.Text;
user.LastName = txtLastName.Text;
user.Member_Username = txtUserName.Text;
user.Password = txtPassword.Text;
user.Email = txtEmail.Text;
user.Gender = rdoGender.SelectedValue;
//reading values that allow null in the database (date of birth)
if (string.IsNullOrEmpty(txtDOB.Text))
{
user.DateofBirth = null;
}
else
{
user.DateofBirth = DateTime.Parse(txtDOB.Text);
}
//call the addMember method
user.AddMember();
//redirect the user to homePage
Response.Redirect("Login.aspx");
}
}
can you try when you add parameters like ( cmd.parameters.addwithvalue("#role",value).
I would like to insert a record into my RDV Table.
This is the query creation of my table
CREATE TABLE [dbo].[RDV] (
[idRdv] INT NOT NULL,
[objet] NVARCHAR (50) NULL,
[objectif] NVARCHAR (50) NULL,
[DateRdv] DATETIME NULL,
[commentaire] NVARCHAR (50) NULL,
[archive] NVARCHAR (50) NULL,
[idClient] INT NULL,
[idUser] INT NULL,
[idResultat] INT NULL,
CONSTRAINT [PK_RDV] PRIMARY KEY CLUSTERED ([idRdv] ASC),
FOREIGN KEY ([idClient]) REFERENCES [dbo].[Client] ([idClient]),
FOREIGN KEY ([idUser]) REFERENCES [dbo].[User] ([idUser]),
FOREIGN KEY ([idResultat]) REFERENCES [dbo].[Resultat] ([idResultat]);
and this is my code of insert
public RDV()
{
InitializeComponent();
textBox3.Visible = false;
label7.Visible = false;
}
private void btnAdd_Click(object sender, EventArgs e)
{
Random rdm = new Random();
int num = rdm.Next(5, 2000);
textBox3.Text = num.ToString();
string cmdStr = "Insert into RDV (idRdv,idUser,idClient,objet,objectif,DateRdv,commentaire) select #idRdv,#idUser,#idClient,#objet,#objectif,#DateRdv,#commentaire from RDV, Client, [User] where RDV.idClient = Client.idClient and RDV.idUser = [User].idUser ";
SqlConnection con = new SqlConnection("Data Source=ADMIN-PC\\SQLEXPRESS;Initial Catalog=timar;Integrated Security=True");
SqlCommand cmd = new SqlCommand(cmdStr, con);
cmd.Parameters.AddWithValue("#idRdv", textBox3.Text);
cmd.Parameters.AddWithValue("#idUser", (comboBox1.SelectedValue));
cmd.Parameters.AddWithValue("#idClient", (comboBox2.SelectedValue));
cmd.Parameters.AddWithValue("#objet", textBox1.Text);
cmd.Parameters.AddWithValue("#objectif", textBox2.Text);
cmd.Parameters.AddWithValue("#DateRdv", dateTimePicker1.Value.ToString());
cmd.Parameters.AddWithValue("#commentaire", textBox4.Text);
con.Open();
int LA = cmd.ExecuteNonQuery();
Console.WriteLine("Ligne ajoutée: {0}", LA);
And,the field idRdv , i want to add it but should be hidden and Random like in the code above.
When , I run my project , it shows me an error Violation of PRIMARY KEY " PK_RDV ". Can not insert duplicate key in object ' dbo.RDV ". Value of Duplicate Key:1505 (this the value of idRdv)
Pleaaaaseee, help me. How should I correct it.
Thanks in advance
You are using the ID with Random. As your table ID column is containing Primary Key Constraint it may get this error.
Either you check that the random number generated is not exist in the table before insert. Or use a method to get Max(ID)+1 and set this as new ID
I am making a gym management system and I am using foreign keys in my tables. Everything was working perfectly, but after I added foreign keys I am getting the following error:
SQLException was Unhandled
The INSERT statement conflicted with the FOREIGN KEY constraint
"FK_member_info_instructor_info". The conflict occurred in database "D:\GYM MANAGEMENT
SYSTEM\GYM MANAGEMENT SYSTEM\BIN\DEBUG\GMSDATABASE.MDF", table "dbo.instructor_info",
column 'InstructorID'.
The statement has been terminated.
This error is pointing to this code:
public void UpdateDatabase(System.Data.DataSet ds)
{
System.Data.SqlClient.SqlCommandBuilder cb = new
System.Data.SqlClient.SqlCommandBuilder(da_1);
cb.DataAdapter.Update(ds.Tables[0]);
}
The above code is in my database collection class which is as following:
class GMSDConnectionClass
{
System.Data.SqlClient.SqlDataAdapter da_1;
System.Data.SqlClient.SqlConnection con;
public string sql_string;
public string strCon;
public string Sql
{
set { sql_string = value; }
}
public string connection_string
{
set { strCon = value; }
}
public System.Data.DataSet GetConnection
{
get { return MyDataSet(); }
}
public System.Data.DataSet MyDataSet()
{
con = new System.Data.SqlClient.SqlConnection(strCon);
con.Open();
da_1 = new System.Data.SqlClient.SqlDataAdapter(sql_string, con);
System.Data.DataSet dat_set = new System.Data.DataSet();
da_1.Fill(dat_set, "Table_data_1");
con.Close();
return dat_set;
}
public void UpdateDatabase(System.Data.DataSet ds)
{
System.Data.SqlClient.SqlCommandBuilder cb = new
System.Data.SqlClient.SqlCommandBuilder(da_1);
cb.DataAdapter.Update(ds.Tables[0]);
}
}
These are my tables which are being used when the error is thrown:
instructor_info table:
CREATE TABLE [dbo].[instructor_info] (
[InstructorID] INT IDENTITY (1, 1) NOT NULL,
[instructor] NVARCHAR (50) NOT NULL,
[father_name] NVARCHAR (50) NULL,
[age] NCHAR (10) NULL,
[address] NVARCHAR (MAX) NULL,
[contact] NVARCHAR (50) NULL,
[height] NCHAR (10) NULL,
[weight] NCHAR (10) NULL,
[chest] NCHAR (10) NULL,
[triceps_biceps] NCHAR (10) NULL,
[waist] NCHAR (10) NULL,
[shoulders] NCHAR (10) NULL,
[thighs] NCHAR (10) NULL,
[calves] NCHAR (10) NULL,
[memberID] INT NULL,
[date_of_admission] DATE NULL,
[photo] IMAGE NULL,
PRIMARY KEY CLUSTERED ([InstructorID] ASC),
CONSTRAINT [FK_instructor_info_member_info] FOREIGN KEY ([memberID]) REFERENCES [dbo].
[member_info] ([memberID])
);
member_info table:
CREATE TABLE [dbo].[member_info] (
[memberID] INT IDENTITY (1, 1) NOT NULL,
[memberName] NVARCHAR (50) NULL,
[father_name] NVARCHAR (50) NULL,
[age] NCHAR (10) NULL,
[address] NVARCHAR (50) NULL,
[contact] NVARCHAR (50) NULL,
[height] NVARCHAR (50) NULL,
[weight] NVARCHAR (50) NULL,
[chest] NVARCHAR (50) NULL,
[triceps_biceps] NVARCHAR (50) NULL,
[waist] NVARCHAR (50) NULL,
[shoulders] NVARCHAR (50) NULL,
[thighs] NVARCHAR (50) NULL,
[calves] NVARCHAR (50) NULL,
[instructorID] INT NULL,
[date_of_admission] DATE NULL,
[photo] IMAGE NULL,
PRIMARY KEY CLUSTERED ([memberID] ASC),
CONSTRAINT [FK_member_info_instructor_info] FOREIGN KEY ([instructorID]) REFERENCES
[dbo].[instructor_info] ([InstructorID])
);
This is my code for the save button on my form:
private void saveBtn_Click(object sender, EventArgs e)
{
DataRow row = memberDataS.Tables[0].NewRow();
row[0] = maxRowsMember + 1;
row[1] = memberName.Text;
row[2] = fatherName.Text;
row[3] = age.Text;
row[4] = address.Text;
row[5] = contact.Text;
row[6] = height.Text;
row[7] = weight.Text;
row[8] = chest.Text;
row[9] = tricepBicep.Text;
row[10] = waist.Text;
row[11] = shoulders.Text;
row[12] = thighs.Text;
row[13] = calves.Text;
row[14] = int.Parse(instructor.Text);
row[15] = dateTimePicker1.Text;
memberDataS.Tables[0].Rows.Add(row);
memberString.UpdateDatabase(memberDataS);
maxRowsMember += 1;
inc = maxRowsMember - 1;
MessageBox.Show("Database updated");
cancelBtn.Enabled = false;
saveBtn.Enabled = false;
addNewMemberBtn.Enabled = true;
}
All help will be appreciated. Thanks a lot.
I believe that your error may be resulting from row 14:
row[14] = int.Parse(instructor.Text);
If my assumption about your code is correct, the instructor variable contains the VARCHAR(50) instructor name, not the INT IDENTITY value of instructorID.
How can I pass a DataTable from C# to SQL Server 2008?
Exception:
The table type parameter '#CurrentTableInitial' must have a valid type
name.
Table structure:
CREATE TABLE [dbo].[RegisterChoiceUserInitial](
[RegisterChoiceUserInitialID] [int] IDENTITY(1,1) NOT NULL,
[UserId] [uniqueidentifier] NOT NULL,
[RegisterChoiceUserInitialJob] [nvarchar](50) NULL,
[RegisterChoiceUserInitialOrganization] [nvarchar](50) NULL,
[RegisterChoiceUserInitialUnit] [nvarchar](50) NULL,
[RegisterChoiceUserInitialMembershipType] [nvarchar](50) NULL,
[RegisterChoiceUserInitialStart] [nvarchar](10) NULL,
[RegisterChoiceUserInitialEnd] [nvarchar](10) NULL,
CONSTRAINT [PK_RegisterChoiceUserInitial] PRIMARY KEY CLUSTERED
(
[RegisterChoiceUserInitialID] ASC
)
User-defined type:
CREATE TYPE [dbo].[TableTypeInitial] AS TABLE(
[ID] [int] NULL,
[InitialJob] [nvarchar](50) NULL,
[InitialOrganization] [nvarchar](50) NULL,
[InitialUnit] [nvarchar](50) NULL,
[InitialMembershipType] [nvarchar](50) NULL,
[InitialMembershipStart] [nvarchar](10) NULL,
[InitialMembershipEnd] [nvarchar](10) NULL
)
Stored procedure:
create PROCEDURE [dbo].[FinishRegisterChoiceUserInitial]
( #UserId uniqueidentifier,
#TableVariable TableTypeInitial READONLY)
AS
BEGIN
INSERT INTO [Election].[dbo].[RegisterChoiceUserInitial]
([UserId]
,[RegisterChoiceUserInitialJob]
,[RegisterChoiceUserInitialOrganization]
,[RegisterChoiceUserInitialUnit]
,[RegisterChoiceUserInitialMembershipType]
,[RegisterChoiceUserInitialStart]
,[RegisterChoiceUserInitialEnd])
SELECT
#UserId AS UserId
,InitialJob
,InitialOrganization
,InitialUnit
,InitialMembershipType
,InitialMembershipStart
,InitialMembershipEnd
FROM
#TableVariable
END
DataTable:
DataTableInitial.Columns.Add(new DataColumn("ID", typeof(int)));
DataTableInitial.Columns.Add(new DataColumn("InitialJob", typeof(String)));
DataTableInitial.Columns.Add(new DataColumn("InitialOrganization", typeof(String)));
DataTableInitial.Columns.Add(new DataColumn("InitialUnit", typeof(String)));
DataTableInitial.Columns.Add(new DataColumn("InitialMembershipType", typeof(String)));
DataTableInitial.Columns.Add(new DataColumn("InitialMembershipStart", typeof(String)));
DataTableInitial.Columns.Add(new DataColumn("InitialMembershipEnd", typeof(String)));
cmd.CommandText = "EXEC FinishRegisterChoiceUserInitial #UserId, #CurrentTableInitial ";
cmd.Parameters.AddWithValue("#UserId",user.ProviderUserKey);
DataTable TableInitial=(DataTable)ViewState["CurrentTableInitial"];
SqlParameter a = cmd.Parameters.AddWithValue("#CurrentTableInitial", TableInitial);
a.SqlDbType = SqlDbType.Structured;
cmd.ExecuteNonQuery();
You were missing a.TypeName = "dbo.TableTypeInitial";
Put this statement before "a.SqlDbType = SqlDbType.Structured;"
Use
cmd.CommandText = "EXEC FinishRegisterChoiceUserInitial #UserId, #TableTypeInitial ";
instead of
cmd.CommandText = "EXEC FinishRegisterChoiceUserInitial #UserId, #CurrentTableInitial ";
Sql Server Scripts :
CREATE TABLE [Target]
(
[ID] [int] NOT NULL PRIMARY KEY IDENTITY,
[FirstName] [varchar](100)NOT NULL,
[LastName] [varchar](100)NOT NULL,
[Email] [varchar](200) NOT NULL
)
CREATE TYPE [TargetUDT] AS TABLE
(
[FirstName] [varchar](100)NOT NULL,
[LastName] [varchar](100)NOT NULL,
[Email] [varchar](200) NOT NULL
)
CREATE PROCEDURE AddToTarget(#TargetUDT TargetUDT READONLY)
AS
BEGIN
INSERT INTO [Target]
SELECT * FROM #TargetUDT
END
Sample Code :
public static void StartProcess()
{
//Create a local data table to hold customer records
DataTable dtCustomers = new DataTable("Customers");
DataColumn dcFirstName = new DataColumn("FirstName", typeof(string));
DataColumn dcLastName = new DataColumn("LastName", typeof(string));
DataColumn dcEmail = new DataColumn("Email", typeof(string));
dtCustomers.Columns.Add(dcFirstName);
dtCustomers.Columns.Add(dcLastName);
dtCustomers.Columns.Add(dcEmail);
//Add customer 1
DataRow drCustomer = dtCustomers.NewRow();
drCustomer["FirstName"] = "AAA";
drCustomer["LastName"] = "XYZ";
drCustomer["Email"] = "aaa#test.com";
dtCustomers.Rows.Add(drCustomer);
//Add customer 2
drCustomer = dtCustomers.NewRow();
drCustomer["FirstName"] = "BBB";
drCustomer["LastName"] = "XYZ";
drCustomer["Email"] = "bbb#test.com";
dtCustomers.Rows.Add(drCustomer);
//Add customer 3
drCustomer = dtCustomers.NewRow();
drCustomer["FirstName"] = "CCC";
drCustomer["LastName"] = "XYZ";
drCustomer["Email"] = "ccc#test.com";
dtCustomers.Rows.Add(drCustomer);
//Create Connection object to connect to server/database
SqlConnection conn = new SqlConnection(ConStr);
conn.Open();
//Create a command object that calls the stored procedure
SqlCommand cmdCustomer = new SqlCommand("AddToTarget", conn);
cmdCustomer.CommandType = CommandType.StoredProcedure;
//Create a parameter using the new SQL DB type viz. Structured to pass as table value parameter
SqlParameter paramCustomer = cmdCustomer.Parameters.Add("#TargetUDT", SqlDbType.Structured);
paramCustomer.Value = dtCustomers;
//Execute the query
cmdCustomer.ExecuteNonQuery();
}