首页 > 解决方案 > 是否可以通过SqlDataReader 获取SQL 列的长度?

问题描述

使用 SqlDataReader,我可以获得列名和 SQL 数据类型,但我似乎找不到获取长度、精度或比例的方法。还有另一种方法可以获取每列的数据吗?

代码:

using System;
using System.Data;
using System.Data.SqlTypes;
using System.Data.SqlClient;
using Microsoft.SqlServer.Server;

public class StoredProcedures
{
 [SqlProcedure]
    public static void CLRExec(SqlString query)
    {
        SqlContext.Pipe.Send(DateTime.Now.ToString() + " -- " + query.ToString());
        using (SqlConnection connection = new SqlConnection("context connection=true"))
        {
            string sQuery = query.ToString();

            // Create the record and specify the metadata for the columns.
            SqlDataRecord record = new SqlDataRecord(
                new SqlMetaData("col1", SqlDbType.NVarChar, 100),
                new SqlMetaData("col2", SqlDbType.NVarChar, 100));

            connection.Open();
            SqlCommand command = new SqlCommand(sQuery, connection);
            SqlDataReader reader = command.ExecuteReader();
            //DataTable table = reader.GetSchemaTable();


            // Mark the begining of the result-set.
            SqlContext.Pipe.SendResultsStart(record);

            for (int i = 0; i < reader.FieldCount; i++)
            {
                record.SetString(0, reader.GetName(i).ToString());
                record.SetString(1, reader.GetDataTypeName(i).ToString());

                // Send the row back to the client.
                SqlContext.Pipe.SendResultsRow(record);
            }

            SqlContext.Pipe.SendResultsEnd();
        }
    }
}

标签: c#sqlclr

解决方案


推荐阅读