sql >> Database teknologi >  >> RDS >> Sqlserver

Hvordan udføres denne SQL-forespørgsel ved hjælp af ADO.NET?

Jeg bruger en ændring af din originale SQL til eksempelformål.

DECLARE @list AS TABLE (Name VARCHAR(20));
INSERT INTO @list(Name)
VALUES ('PROCEDURE'), 
        ('FUNCTION');

SELECT *
FROM INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_TYPE in (SELECT Name from @list)

Du kan bruge en tabelværdiparameter

Her er et modificeret eksempel taget fra Table-Valued Parameters i SQL Server 2008 (ADO. NET)

        using (SqlConnection cnn = new SqlConnection("Your connection string"))
        {

            var tableParam = new DataTable("names");
            tableParam.Columns.Add("Name", typeof(string));
            tableParam.Rows.Add(new object[] { "PROCEDURE" });
            tableParam.Rows.Add(new object[] { "FUNCTION')" });

            var sql = @"DECLARE @list AS TABLE (Name VARCHAR(20))
                       INSERT INTO @list(Name)
                       SELECT Name from @Names;

                       SELECT *
                       FROM INFORMATION_SCHEMA.ROUTINES
                       WHERE ROUTINE_TYPE in (SELECT Name from @list)";

            var sqlCmd = new SqlCommand(sql, cnn);
            var tvpParam = sqlCmd.Parameters.AddWithValue("@Names", tableParam);
            tvpParam.SqlDbType = SqlDbType.Structured;
            tvpParam.TypeName = "dbo.Names";

            cnn.Open();
            using(SqlDataReader rdr = sqlCmd.ExecuteReader() )
            {
                while (rdr.Read())
                    Console.WriteLine(rdr["SPECIFIC_NAME"]);                    

            }



        }

Men du skal definere typen dbo.Names, før det kan virke

Her er typen skabelse SQL

CREATE TYPE dbo.Names AS TABLE 
( Name VARCHAR(Max));

En anden mulighed er at bruge en XML-parameter

 using (SqlConnection cnn = new SqlConnection("Your connection string"))
{



    var sql = @"DECLARE @list AS TABLE (Name VARCHAR(20))
                INSERT INTO @list(Name)
                SELECT t.name.value('.', 'varchar(MAX)')
                FROM   @Names.nodes('/Names/Name') as T(Name);

                SELECT *
                FROM INFORMATION_SCHEMA.ROUTINES
                WHERE ROUTINE_TYPE in (SELECT Name from @list)";

    var sqlCmd = new SqlCommand(sql, cnn);

    var s = new MemoryStream(ASCIIEncoding.Default.GetBytes("<Names><Name>PROCEDURE</Name><Name>FUNCTION</Name></Names>"));


    var xmlParam = new SqlXml(s);

    sqlCmd.Parameters.AddWithValue("@Names", xmlParam);


    cnn.Open();
    using(SqlDataReader rdr = sqlCmd.ExecuteReader() )
    {
        while (rdr.Read())
            Console.WriteLine(rdr["SPECIFIC_NAME"]);                    

    }



}



  1. Hvordan kører man et program fra SQL?

  2. SQL Server System Databaser – Grundlæggende koncepter

  3. Parameter Sniffing Primer

  4. Frigør fordelene ved MariaDBs Certified Associate Program