I want to pass a table parameter to SQL Server 2008. Most of what I find on the Internet talks about doing this with a stored procedure, but is it possible to also do it with an Ad-Hoc query? With the code below, I get the error, "Column, parameter, or variable @idList. : Cannot find data type dbo.SiteType.". I think it might be executing the type definition as a totally separate query and 'forgetting' about it when the SELECT is initiated.
DataTable dt = new DataTable();
dt.Columns.Add("ID", Type.GetType("System.Guid"));
foreach (Guid guid in filter.FetchIDs)
{
DataRow row = dt.NewRow();
row["ID"] = guid;
}
sqlCmd.CommandText = "CREATE TYPE [dbo].[SiteType] AS TABLE(ID uniqueidentifier);" + "SELECT * FROM Site INNER JOIN @idList as FetchIDs on FetchIDs.ID=Site.ID;";
SqlParameter parameter = sqlCmd.Parameters.AddWithValue("@idList", dt);
parameter.TypeName = "[dbo].[SiteType]";
UPDATE: I added 'dbo.SiteType' as a type to the database, and now using this code it works, but returns zero rows:
DataTable dt = new DataTable();
dt.Columns.Add("ID", Type.GetType("System.Guid"));
foreach (Guid guid in filter.FetchIDs)
{
DataRow row = dt.NewRow();
row["ID"] = guid;
}
sqlCmd.CommandText = "SELECT * FROM Site INNER JOIN @idList as FetchIDs on FetchIDs.ID=Site.ID;";
SqlParameter parameter = sqlCmd.Parameters.Add("@idList", SqlDbType.Structured);
parameter.TypeName = "[dbo].[SiteType]";
parameter.Value = dt;