/* ------------------------ My Meta Content Here SEO ------------------------ */

Pages

Main Menu

Saturday, May 4, 2019

ADO.NET

How to Create and Execute SqlCommand in ADO.NET


ADO.NET, Data Access, .NET Development

Stored Procedures, sql commond

How to Create and Execute SqlCommand in ADO.NET

Introduction

We can create and execute different types of SqlCommand. In this applilcation, we will demonstrate how to create and execute SqlCommand:

1. Create different types of SqlCommand;
2. Execute SqlCommand in different ways;
3. Display the result.

Using the Code

1. ExecuteNonQuery method
If you need modify the data (Add, Delete, Update), you can use the method to complete it.

C#

public static Int32 ExecuteNonQuery(String connectionString, String commandText,  
    CommandType commandType, params SqlParameter[] parameters) 
{ 
    using (SqlConnection conn = new SqlConnection(connectionString)) 
    { 
        using (SqlCommand cmd = new SqlCommand(commandText, conn)) 
        { 
            cmd.CommandType = commandType; 
            cmd.Parameters.AddRange(parameters); 
            conn.Open(); 
            return cmd.ExecuteNonQuery(); 
        } 
    } 
} 

2. ExecuteScalar method
If you only need one value (first column and first row), you can use the method to get the value, such as the statistical value.

C#

public static Object ExecuteScalar(String connectionString, String commandText, 
    CommandType commandType, params SqlParameter[] parameters) 
{ 
    using (SqlConnection conn = new SqlConnection(connectionString)) 
    { 
        using (SqlCommand cmd = new SqlCommand(commandText, conn)) 
        { 
            cmd.CommandType = commandType; 
            cmd.Parameters.AddRange(parameters); 
            conn.Open(); 
            return cmd.ExecuteScalar(); 
        } 
    } 
} 

3. ExecuteReader method
When you need the details of the data, you can use this method to return the information.

C#

public static SqlDataReader ExecuteReader(String connectionString, String commandText,  
    CommandType commandType, params SqlParameter[] parameters) 
{ 
    SqlConnection conn = new SqlConnection(connectionString); 
    using (SqlCommand cmd = new SqlCommand(commandText, conn)) 
    { 
        cmd.CommandType = commandType; 
        cmd.Parameters.AddRange(parameters); 
        conn.Open(); 
        // When using CommandBehavior.CloseConnection, the connection will be closed when the // IDataReader is closed. 
        SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection); 
        return reader; 
    } 
} 

4. Parameter
You can add several parameters to the command and set the properties of parameter, such as the value, the type and the direction. If the direction is set as Output, you can get the value of parameter after executing the command.

C#

// Specify the year of StartDate 
SqlParameter parameterYear = new SqlParameter("@Year", SqlDbType.Int); 
parameterYear.Value = year; 
SqlParameter parameterBudget = new SqlParameter("@BudgetSum", SqlDbType.Money); 
parameterBudget.Direction = ParameterDirection.Output; 

5. Command Type.
There're three command types: StoredProcedure, Text (Default), TableDirect. The TableDirect type is only for OLE DB.

C#

using (SqlDataReader reader = SqlHelper.ExecuteReader(connectionString, commandText,  
               CommandType.StoredProcedure, parameterYear, parameterBudget)) 
Read More »

Monday, December 17, 2018

Validation to Check Duplicate Records

Prevent from inserting duplicate records into the table

You need to check if a duplicate entry exists in table before inserting the data. I suggest you could refer to the solution given below:

Approach 1=>

using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultCSRConnection"].ConnectionString))
            {
                //Open your connection
                conn.Open();

                //Your Select Query
                //Change this as per your design and provide the primary key field here
                string selectString = "SELECT COUNT(*) FROM tbl_students WHERE YourIDField = @idfield";

                //Create Command object
                SqlCommand myCommand = new SqlCommand(selectString, conn);

                //Pass your parameter here
                myCommand.Parameters.AddWithValue("@id", yourexistingidvalue);

                // Get the Result query
                var idExists = (Int32)myCommand.ExecuteScalar() > 0;

                //Check if record exists in table
                if (!idExists)
                {
                    //Insert the Record
                    using (SqlCommand cmd = conn.CreateCommand())
                    {
                        SqlCommand cmd1 = new SqlCommand("Insert into tbl_students (first_name,last_name,sex,dob,active) values(@first_name, @last_name,@sex,@dob,@active)", conn);
                        cmd1.Parameters.Add("@first_name", SqlDbType.NVarChar).Value = txtFname.Text;
                        cmd1.Parameters.Add("@last_name", SqlDbType.NVarChar).Value = txtLname.Text;
                        cmd1.Parameters.Add("@sex", SqlDbType.NVarChar).Value = ddlgender.SelectedValue;
                        cmd1.Parameters.Add("@dob", SqlDbType.DateTime).Value = txtDateofBirth.Text;
                        cmd1.Parameters.Add("@active", SqlDbType.Bit).Value = Convert.ToInt32(ddlActiveInactive.SelectedValue);
                        cmd1.ExecuteNonQuery();
                        conn.Close();
                        ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('page added sucessfully');window.location ='csrstudentprofile.aspx';", true);
                    }
                }
            }
Approach 2=>

CREATE PROC ValidateAndInsertStudent
(
@first_name VARCHAR(50),
@last_name VARCHAR(50),
@sex VARCHAR(50),
@dob DateTime,
@active BIT,
@Done BIT,
@Msg VARCHAR(200)
)
AS 
BEGIN
 SET @Done = 1,
 SET @Msg = ''
 IF (SELECT COUNT(*) FROM tbl_students WHERE first_name=@first_name AND last_name=@last_name AND sex=@sex AND dob=@dob AND active=@active)>0
 BEGIN
  SET @Done = 0
  SET @Msg = 'Record exists'
  RETURN;
 END
 Insert into tbl_students (first_name,last_name,sex,dob,active) values(@first_name, @last_name,@sex,@dob,@active)
END
Approach 3=> Using Output Parameter

CREATE PROCEDURE [dbo].[InsertsFruitName]
      @FruitId INT,
      @Exists VARCHAR(30OUTPUT,
      @Details VARCHAR(300) 
AS
BEGIN
      SET NOCOUNT ON;
      IF EXISTS (SELECT TOP 1 FROM Fruits WHERE FruitId = @FruitId)
      BEGIN
      SELECT @Exists = 'EXISTS' 
     END
     ELSE
     BEGIN
         SELECT @Exists = '' 
         INSERT INTO Fruits (Details) VALUES                                              (@Details) WHERE FruitId = @FruitId
     END
END

Return Output parameter from Stored Procedure in ASP.Net

protected void Submit(object sender, EventArgs e)
{
    string constring = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con = new SqlConnection(constring))
    {insert
        using (SqlCommand cmd = new SqlCommand("InsertsFruitName", con))
        {
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@FruitId"int.Parse(txtFruitId.Text.Trim()));
cmd.Parameters.AddWithValue("@Details"int.Parse(txtFruitDetails.Text.Trim()));
            cmd.Parameters.Add("@Exists"SqlDbType.VarChar, 30);
            cmd.Parameters["@Exists"].Direction = ParameterDirection.Output;
            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();
IF(cmd.Parameters["@Exists"].Value.ToString() == "")
{
            lblFruitName.Text = "Fruit Details Added Successfully."';
}
else
{
            lblFruitName.Text = "Fruits Details Already Exists";
}
        }
    }
}



Read More »

Monday, October 29, 2018

Converting String in to CSV files in C Sharp







Function For Creating CSV files in C#

public static string FormatCSV(string input)
    {
        try
        {
            if (input == null)
                return string.Empty;

            bool containsQuote = false;
            bool containsComma = false;
            int len = input.Length;
            for (int i = 0; i < len && (containsComma == false || containsQuote == false); i++)
            {
                char ch = input[i];
                if (ch == '"')
                    containsQuote = true;
                else if (ch == ',')
                    containsComma = true;
            }

            if (containsQuote && containsComma)
                input = input.Replace("\"", "\"\"");

            if (containsComma)
                return "\"" + input + "\"";
            else
                return input;
        }
        catch
        {
            throw;
        }
    }
Read More »

Thursday, November 16, 2017

How to split comma separated value in sql server

How to split comma separated value in SQL server :

----- Approach 1:  Common Table Expression (CTE) ----- Lets call this function as Split2.  here we are using
CREATE FUNCTION dbo.Split2 ( @strString varchar(4000))
RETURNS  @Result TABLE(Value BIGINT)
AS
begin
    WITH StrCTE(start, stop) AS
    (
      SELECT  1, CHARINDEX(',' , @strString )
      UNION ALL
      SELECT  stop + 1, CHARINDEX(',' ,@strString  , stop + 1)
      FROM StrCTE
      WHERE stop > 0
    )   
    insert into @Result
    SELECT   SUBSTRING(@strString , start, CASE WHEN stop > 0 THEN stop-start ELSE 4000 END) AS stringValue
    FROM StrCTE  
    return
end
GO

----- Approach 2:  XML (surprise) ----- XML could be applied to do some type of string parsing (see this) Let’s call this function as Split3.
CREATE FUNCTION dbo.Split3 ( @strString varchar(4000))
RETURNS  @Result TABLE(Value BIGINT)
AS
BEGIN
      DECLARE @x XML
      SELECT @x = CAST(''+ REPLACE(@strString,',','')+ '' AS XML)    
      INSERT INTO @Result           
      SELECT t.value('.', 'int') AS inVal
      FROM @x.nodes('/A') AS x(t)
    RETURN
END 
GO

----- Approach 3: Classic TSQL Way ----- This approach is slightly unusual but very effective. this needs you to create a table of sequential numbers called a Tally Table.
SELECT TOP 11000 --equates to more than 30 years of dates     
IDENTITY(INT,1,1) AS N 
INTO dbo.Tally 
FROM Master.dbo.SysColumns sc1,     
Master.dbo.SysColumns sc2

----- Lets index the table for better performance. -----
ALTER TABLE dbo.Tally 
ADD CONSTRAINT PK_Tally_N PRIMARY KEY CLUSTERED (N)
WITH FILLFACTOR = 100

----- Finally out Split4 function. -----
CREATE FUNCTION dbo.Split4 ( @strString varchar(4000))
RETURNS  @Result TABLE(Value BIGINT)
AS
BEGIN
      SET @strString = ','+@strString +','
      INSERT INTO @t  (Value)
      SELECT SUBSTRING(@strString,N+1,CHARINDEX(',',@strString,N+1)-N-1) 
      FROM dbo.Tally
      WHERE N < LEN(@strString) 
      AND SUBSTRING(@strString,N,1) = ',' --Notice how we find the comma
      RETURN
END 
GO

----- so I changed the code slightly to test out XML function directly and copied data ia a temporary table -----
--declare @str varchar(4000) = '1,2,3,4,5,6'
declare @str varchar(4000) = 'A,B,C,D,E,F'
declare @xml XML
select @xml = cast(''+REPLACE(@str,',','')+'' as XML)
select * into tempTable  from  (select t.value('.', 'VARCHAR') as inVal from @xml.nodes('/A') as x(t)) as tbl
select * from tempTable

----- so I changed the code slightly to test out XML function directly and copied data using Table Variable Parameter -----
--declare @str varchar(4000) = '1,2,3,4,5,6'
declare @temp table(VALUE nvarchar(100))
declare @str varchar(4000) = 'A,B,C,D,E,F'
declare @xml XML
select @xml = cast(''+REPLACE(@str,',','')+'' as XML)
insert into @temp select t.value('.', 'VARCHAR') as inVal from @xml.nodes('/A') as x(t)
select * from @temp

Read More »

My Blog List