2009-12-07 64 views
1

我試圖通過調用使用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

你可以在SQL Server設置檢查了這一點,看看什麼東西跨線實際去。 – 2009-12-07 21:36:32

+0

偉大的代碼示例謝謝! – scarpacci 2011-12-04 23:26:05

回答

4

補充一點:

cmd.CommandType = CommandType.StoredProcedure; 
+0

良好的通話!你可以告訴它已經有一段時間了,因爲我已經完成了原始的ADO.NET!這些天我使用NHibernate或企業庫。 – 2009-12-08 01:41:59

相關問題