我正在尝试将用户定义的表类型传递给 C# 中的查询。
类型定义为 2 列(组织和子组织)
这就是我的代码的样子:
DataSet ds = new DataSet();
try
{
DataTable FilteredOrgSubOrg = new DataTable("OrgSubOrgValueType");
FilteredOrgSubOrg.Columns.Add("org", typeof(string));
FilteredOrgSubOrg.Columns.Add("subOrg", typeof(string));
FilteredOrgSubOrg.Rows.Add(org, orgsub);
using (SqlConnection conn = new SqlConnection(cCon.getConn()))
{
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText =
"select * from myTable ex where year = @year' and qtr = @qtr" +
" and EXISTS(SELECT 1 FROM @OrgSubOrg tt WHERE ex.org like tt.org" +
" AND ex.orgsub = tt.suborg )"+
" order by ex.org,year, qtr DESC";
// 2. set the command object so it knows
// to execute a stored procedure
// 3. add parameter to command, which
// will be passed to the stored procedure
cmd.Parameters.Add(new SqlParameter("@OrgSubOrg", FilteredOrgSubOrg));
cmd.Parameters.Add(new SqlParameter("@year", year));
cmd.Parameters.Add(new SqlParameter("@qtr", qtr));
conn.Open();
SqlDataAdapter sqlDA = new SqlDataAdapter();
sqlDA.SelectCommand = cmd;
sqlDA.Fill(ds);
}
}
我是否错误地传递了参数?
当我像这样在 SQL Server 中执行此操作时:
declare @OrgSubOrg OrgSubOrgValueType
insert into @OrgSubOrg values ('05%','00000000')
insert into @OrgSubOrg values ('03%','00000000')
------------ complete -----------------------------------
select * from myTable ex
where
year = '2013' and qtr = '1'
and EXISTS(
SELECT 1
FROM @OrgSubOrg tt
WHERE ex.org like tt.org
AND ex.orgsub = tt.suborg )
order by ex.org,year, qtr DESC
everything works like it should.
我也尝试像这样传递它:
SqlParameter p = cmd.Parameters.Add(new SqlParameter("@OrgSubOrg", SqlDbType.Structured));
p.Value = FilteredOrgSubOrg;
但我得到了同样的错误
The table type parameter '@OrgSubOrg' must have a valid type name.
可能是我不能将它传递给 SQL 命令吗?我在另一个地方有类似的代码,它适用于存储过程......?