Stored Procedures 2018-11-18
Stored Procedure – Förarbete CREATE TABLE tbl_Students ( [Studentid] [int] IDENTITY(1,1) NOT NULL, [Firstname] [nvarchar](200) NOT NULL, [Lastname] [nvarchar](200) NULL, [Email] [nvarchar](100) NULL ) Insert into tbl_Students (Firstname, lastname, Email) Values('Vivek', 'Johari', 'vivek@abc.com') Values('Pankaj', 'Kumar', 'pankaj@abc.com') Values('Amit', 'Singh', 'amit@abc.com') Values('Manish', 'Kumar', 'manish@abc.comm')
Hur ser en Stored Procedure ut? Create Procedure Procedure-name ( Input parameters , Output Parameters (If required) ) As Begin Sql statement used in the stored procedure End
Exempel /* GetstudentnameInOutputVariable is the name of the stored procedure which uses output variable @Studentname to collect the student name returns by the stored procedure */ Create PROCEDURE GetstudentnameInOutputVariable ( @studentid INT, -- Input parameter, Studentid of the student @studentname VARCHAR(200) OUT -- Out parameter declared with the help of OUT keyword ) AS BEGIN SELECT @studentname= Firstname+' '+Lastname FROM tbl_Students WHERE studentid=@studentid END
/* This Stored procedure is used to Insert value into the table tbl_students. */ Create Procedure InsertStudentrecord ( @StudentFirstName Varchar(200), @StudentLastName Varchar(200), @StudentEmail Varchar(50) ) As Begin Insert into tbl_Students (Firstname, lastname, Email) Values(@StudentFirstName, @StudentLastName,@StudentEmail) End
Hur ser det ut när vi använder C# string connectionString = @"Server=.\SQLEXPRESS; ” + ”Initial Catalog=SPO12; ” + ”Integrated Security=True;"; SqlConnection conn = new SqlConnection(connectionString); SqlCommand cmd = new SqlCommand("dbo.GetstudentnameInOutputVariable"); try { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add(new SqlParameter("@studentid", 1)); SqlParameter nameParameter = new SqlParameter("@studentname", 0); nameParameter.Direction = ParameterDirection.Output; cmd.Parameters.Add(nameParameter); conn.Open(); cmd.Connection = conn;
Hur ser det ut när vi använder C# cmd.ExecuteNonQuery(); string studentName = cmd.Parameters["@studentname"].Value.ToString(); Response.Write("<p>Namnet: " + studentName.ToString()); } Finaly { conn.Close();
Var kan jag finna mera? www.sqlteam.com www.mssqltips.com CodeProject StackOverFlow