到达数据库时,为什么我的表值参数为空?

时间:2009-12-07 21:33:41

标签: sql-server sql-server-2008

我正在尝试通过使用ADO.NET调用存储过程来测试SQL 2008的新表值参数功能,但是我遇到了一个问题,当参数似乎不包含任何行时存储过程。 UDT看起来像这样:

CREATE TYPE [dbo].[PersonType] AS TABLE(
[FirstName] [varchar](50) NULL,
[LastName] [varchar](50) NULL,
[Birthdate] [date] NULL)

存储过程如下所示:

 CREATE PROCEDURE [dbo].[AddPeople]
 (@peopleToAdd dbo.PersonType READONLY)
 AS
 BEGIN
      IF (SELECT COUNT(*) FROM @peopleToAdd) > 0
      BEGIN
           SELECT 'Has rows'
      END
      ELSE
      BEGIN
           SELECT 'Does NOT have rows'
      END
 END

最后,.NET代码是这样的(支撑自己,这很多):

public class Program
{
    static void Main(string[] args)
    {
        PersonCollection people = 
            new PersonCollection()
              {
                 new Person
                 {
                    FirstName = "John",
                    LastName = "Doe",
                    Birthdate = new DateTime(1975, 12, 1)
                 },
                 new Person
                 {
                    FirstName = "Randall",
                    LastName = "Stevens",
                    Birthdate = new DateTime(1935, 7, 10)
                 }
               };

        using(SqlConnection conn = new SqlConnection("Data Source=localhost\\sqlexpress;Initial Catalog=TVPExample;Integrated Security=SSPI;"))
        {
            conn.Open();

            SqlCommand cmd = new SqlCommand("AddPeople", conn);

            SqlParameter parameter = cmd.Parameters.AddWithValue("@peopleToAdd", people);
            parameter.SqlDbType = SqlDbType.Structured;
            parameter.TypeName = "dbo.PersonType";

            string result = cmd.ExecuteScalar().ToString();

            Console.WriteLine(result);
        }
    }
}

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public DateTime Birthdate { get; set; }
}

public class PersonCollection : List<Person>, IEnumerable<SqlDataRecord>
{
    #region Implementation of IEnumerable<SqlDataRecord>
    IEnumerator<SqlDataRecord> IEnumerable<SqlDataRecord>.GetEnumerator()
    {
        SqlDataRecord rec = new SqlDataRecord(
            new SqlMetaData("FirstName", SqlDbType.VarChar, 50), 
            new SqlMetaData("LastName", SqlDbType.VarChar, 50), 
            new SqlMetaData("Birthdate",SqlDbType.Date));

        foreach (Person person in this)
        {
            rec.SetString(0, person.FirstName);
            rec.SetString(1, person.LastName);
            rec.SetDateTime(2, person.Birthdate);
            yield return rec;
        }
    }
    #endregion
}

我以this博客文章为例。我总是得到“不包含行”,但是查看Visual Studio调试器会显示我传入的集合包含我放在那里的两个值。有任何想法吗?我错过了什么?

1 个答案:

答案 0 :(得分:4)

添加:

cmd.CommandType = CommandType.StoredProcedure;