简体   繁体   English

如何通过存储过程将 GUID 参数传递给 SQL 服务器?

[英]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' System.Data.SqlClient.SqlEXception: '程序或 function registro_inscricao 指定了太多 arguments'

Already fix one error.已经修复了一个错误。 Thx to @Klaus.谢谢@克劳斯。 But still can't pass the value of guid to the DB但仍然无法将 guid 的值传递给数据库

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();
        }
      }

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?正如@xantos 所说,您上面提供的代码确实有效,但是 - 您没有包括变量的声明方式,如果“g”绝对是 GUID,或者您尝试传递包含 GUID 作为属性的 object,如你有 @nif 的 Value 属性吗?

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):我重构了您的 C# 代码如下,以包含变量定义(并在完成后处理 SQL 对象 - 自己清理的好习惯):

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.看起来您的问题不在上面的代码中,更有可能您正在尝试传递集合或 object。

Check nif.Value is a single INT value and not a collection (eg INT[])检查nif.Value是单个 INT 值而不是集合(例如 INT[])

Check g is a single GUID value (eg it's not defined as a collection type GUID[] or contains a property for your GUID { SomeProperty = GUID }检查g是单个 GUID 值(例如,它未定义为集合类型 GUID[] 或包含您的 GUID { SomeProperty = GUID } 的属性

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM