Carlos Alves
Carlos Alves

Reputation: 9

How to pass GUID parameters to SQL Server through a stored procedure?

I'm getting my first steps on programming, so I'm a little green at this. Thanks in advance for the help you can give.

The code is this:

SqlConnection myConn = new SqlConnection(ConfigurationManager.ConnectionStrings["CET47ConnectionString"].ConnectionString);
        SqlCommand myCommand = new SqlCommand();


        myCommand.Parameters.AddWithValue("@nome", nome.Value);
        myCommand.Parameters.AddWithValue("@data_de_nascimento", Convert.ToDateTime(data_de_nascimento.Value));
        myCommand.Parameters.AddWithValue("@rua", rua.Value);
        myCommand.Parameters.AddWithValue("@localidade", localidade.Value);
        myCommand.Parameters.AddWithValue("@concelho", concelho.Value);
        myCommand.Parameters.AddWithValue("@codigo_postal", codigopostal1.Value + " - " + codigopostal2.Value);
        myCommand.Parameters.AddWithValue("@pais", pais.Value);
        myCommand.Parameters.AddWithValue("@telefone", telf.Value);
        myCommand.Parameters.AddWithValue("@telemovel", telem.Value);
        myCommand.Parameters.AddWithValue("@email", email.Value);
        myCommand.Parameters.AddWithValue("@nif", nif.Value);

        SqlParameter val_output = new SqlParameter();
        val_output.ParameterName = "@retorno";
        val_output.Direction = ParameterDirection.Output;
        val_output.SqlDbType = SqlDbType.Int;

        myCommand.Parameters.Add(val_output);

        myCommand.CommandType = CommandType.StoredProcedure;
        myCommand.CommandText = "inserir_candidato";

        myCommand.Connection = myConn;
        myConn.Open();
        myCommand.ExecuteNonQuery();

        int valor_retornado = Convert.ToInt32(myCommand.Parameters["@retorno"].Value);

        myConn.Close();

        if (valor_retornado == 0)
        {
            Lbl_message.Text = "O utilizador já existe";

        }
        else
        {
            string caminho = ConfigurationSettings.AppSettings.Get("PathFicheiros");// string que aponta para localhost
            string caminhoPDFs = ConfigurationSettings.AppSettings.Get("PathFicheirosPDFs");// string que aponta para local fisico do ficheir
            string pdfTemplate = caminhoPDFs + "Template\\template.pdf";
            //Response.Write(pdfTemplate);
            //Response.End();

            Guid g = Guid.NewGuid();

            string nomePDF = g + ".pdf";
            string newFile = caminhoPDFs + nomePDF;

            PdfReader pdfr = new PdfReader(pdfTemplate);

            PdfStamper pdfst = new PdfStamper(pdfr, new FileStream(newFile, FileMode.Create));

            AcroFields pdfform = pdfst.AcroFields;

            pdfform.SetField("nome", nome.Value);// o nome é o atributo que esta na template.
            pdfform.SetField("data_de_nascimento", data_de_nascimento.Value);
            pdfform.SetField("rua", rua.Value);
            pdfform.SetField("localidade", localidade.Value);
            pdfform.SetField("concelho", concelho.Value);
            pdfform.SetField("codigo_postal", codigopostal1.Value + "-" + codigopostal2.Value);
            pdfform.SetField("pais", pais.Value);
            pdfform.SetField("telefone", telf.Value);
            pdfform.SetField("telemovel", telem.Value);
            pdfform.SetField("email", email.Value);
            pdfform.SetField("contribuinte", nif.Value);

            pdfst.Close();

SqlConnection myConn2 = new SqlConnection(ConfigurationManager.ConnectionStrings["CET47ConnectionString"].ConnectionString);
SqlCommand myCommand2 = new SqlCommand();

myCommand2.Parameters.AddWithValue("@nif", nif.Value);
myCommand2.Parameters.AddWithValue("@gui", g);

myCommand2.CommandType = CommandType.StoredProcedure;
myCommand2.CommandText = "registro_inscricao";
myCommand2.Connection = myConn2;

myConn2.Open();
myCommand2.ExecuteNonQuery();
myConn2.Close();

The stored procedure

CREATE PROCEDURE registro_inscricao
    @nif as int,
    @gui as uniqueidentifier
AS
BEGIN
    SET NOCOUNT ON;

    BEGIN
        UPDATE registos
        SET registo = @gui
        WHERE nif = @nif
    END
END

And I get this error:

System.Data.SqlClient.SqlEXception: 'Procedure or function registro_inscricao has too many arguments specified'

Already fix one error. Thx to @Klaus. But still can't pass the value of guid to the DB

Upvotes: 0

Views: 1419

Answers (2)

Dragonlaird
Dragonlaird

Reputation: 43

As @xantos said, the code you supplied above does work, however - you didn't include how your variables are declared, if "g" definitely a GUID or are you trying to pass an object that contains a GUID as a property, as you have for the Value property of @nif?

I refactored your C# code as follows, to include the variable definitions (and dispose of the SQL Objects when done - a good practice to clean up after yourself):

static void TestDB()
{
    var nif = new { Value = 100 };
    Guid g = Guid.NewGuid();

    using (SqlConnection myConn2 = new SqlConnection(ConfigurationManager.ConnectionStrings["CET47ConnectionString"].ConnectionString))
    {
        myConn2.Open();
        using (SqlCommand myCommand2 = new SqlCommand())
        {
            myCommand2.Parameters.AddWithValue("@nif", nif.Value);
            myCommand2.Parameters.AddWithValue("@gui", g);

            myCommand2.CommandType = CommandType.StoredProcedure;
            myCommand2.CommandText = "registro_inscricao";
            myCommand2.Connection = myConn2;

            myCommand2.ExecuteNonQuery();
        }
        myConn2.Close();
    }
}

I also created a sample Stored Procedure from your definition, as follows:

CREATE PROCEDURE registro_inscricao
    @nif as int,
    @gui as uniqueidentifier
AS
BEGIN
    SET NOCOUNT ON;

    BEGIN
        PRINT 'GUID: ' + CAST(@gui AS NVARCHAR(50))
        --UPDATE registos
        --SET registo = @gui
        --WHERE nif = @nif
    END
END

The result was, it worked first time.

Looks like your problem isn't in the code above, more likely you are attempting to pass a collection or an object.

Check nif.Value is a single INT value and not a collection (e.g. INT[])

Check g is a single GUID value (e.g. it's not defined as a collection type GUID[] or contains a property for your GUID { SomeProperty = GUID }

Upvotes: 0

Nantharupan
Nantharupan

Reputation: 614

You could try something below.

   using (SqlConnection con = new SqlConnection(dc.Con)) {
        using (SqlCommand cmd = new SqlCommand("registro_inscricao", con)) {
          cmd.CommandType = CommandType.StoredProcedure;
    
            cmd.Parameters.Add("@nif", SqlDbType.Int).Value = nif.Value;
            cmd.Parameters.Add("@gui", SqlDbType.UniqueIdentifier).Value = g;

          con.Open();
          cmd.ExecuteNonQuery();
        }
      }

Upvotes: 1

Related Questions