CREATE TABLE Loans (
loan_nbr INT PRIMARY KEY,
loan_date DATETIME,
loan_amount DECIMAL(15, 2));
-- User-defined table type
CREATE TYPE LoanTable
AS TABLE (
loan_nbr INT PRIMARY KEY,
loan_date DATETIME,
loan_amount DECIMAL(15, 2));
GO
-- Procedure with table valued parameter
-- Must use the READONLY clause
CREATE PROCEDURE InsertLoans
@Loans LoanTable READONLY
AS
INSERT INTO Loans
SELECT loan_nbr, loan_date, loan_amount
FROM @Loans;
GO
-- Declare table variable of the new type
DECLARE @NewLoans LoanTable;
-- Initialize the table variable with data
INSERT INTO @NewLoans
VALUES (1, '20080101', 10000.00),
(2, '20080203', 15000.00),
(3, '20080315', 25000.00);
-- Insert new loans using the table variable as parameter
EXEC InsertLoans @Loans = @NewLoans;
DataTable loans;
loans = new DataTable();
loans.Columns.Add("loan_nbr", typeof(int));
loans.Columns.Add("loan_date", typeof(System.DateTime));
loans.Columns.Add("loan_amount", typeof(decimal));
using(SqlCommand cmd = new SqlCommand("InsertLoans", conn)
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("Loans", loans);
cmd.ExecuteNonQuery();
}
Labels: sql server 2008, t-sql programming