我正在尝试编写视图并从该视图中检索数据,我已经这样做了:
string command = "if OBJECT_ID('try1') IS NOT NULL Drop view try1" +"\n"+"go"+"\n";
command = command + "Create view try1 as select WBSCode,Description,TerritoryCode,AmountReleased,convert(varchar(25),CreatedOn,106) as CreatedOn,IsEnable from WBS where WBSCode like '%" + msrch + "%'";
command = command +"\n"+"go"+"\n"+"select WBSCode,Description,TerritoryCode,AmountReleased,convert(varchar(25),CreatedOn,106) as CreatedOn,IsEnable from try1 where TerritoryCode in (select TerritoryCode from Territory where StateCode='" + mbcode + "')";
SqlCommand cmdd = new SqlCommand(command);
cmdd.Connection = con;
SqlDataAdapter da = new SqlDataAdapter(cmdd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
mngwbsGV1.DataSource = dt;
mngwbsGV1.DataBind();
}
但问题是我在da.Fill(dt)
收到错误:
'go'附近的语法不正确。
'CREATE VIEW'必须是查询批次中的第一个语句 'go'附近的语法不正确。
但是当我在SQL Server 2008中运行它时,它正在运行但没有检索数据
我该怎么办?
答案 0 :(得分:2)
您应该单独创建视图,例如在安装或版本升级期间 - 使用常规SQL脚本。
如果必须在代码中执行此操作 - 您需要这样做:
using(SqlConnection conn = new SqlConnection(--your connection string here--))
{
SqlCommand dropView = new SqlCommand("IF OBJECT_ID('try1') IS NOT NULL DROP VIEW try1", conn);
conn.Open();
dropView.ExecuteNonQuery();
SqlCommand createView = new SqlCommand("CREATE VIEW try1 AS SELECT WBSCode, Description, TerritoryCode, AmountReleased, CONVERT(VARCHAR(25), CreatedOn, 106) AS CreatedOn, IsEnable FROM WBS ", conn);
createView.ExecuteNonQuery();
conn.Close();
}
然后您可以使用它来选择它(使用参数化查询而不是将SQL命令连接在一起以避免SQL注入攻击并提高性能!):
SqlCommand selectCmd = new SqlCommand("SELECT WBSCode, Description, TerritoryCode, AmountReleased, CreatedOn, IsEnable FROM try1 WHERE TerritoryCode IN (SELECT TerritoryCode FROM Territory WHERE WBSCode LIKE @msrch AND StateCode = @mbcode", conn);
selectCmd.Parameters.Add("@msrch", SqlDbType.VarChar, 50).Value = "%" + msrch + "%";
selectCmd.Parameters.Add("@mbcode", SqlDbType.VarChar, 50).Value = mbcode;
SqlDataAdapter da = new SqlDataAdapter(selectCmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
mngwbsGV1.DataSource = dt;
mngwbsGV1.DataBind();
}
但话又说回来:如果你有这样一个简单的选择 - 你首先需要一个视图,特别是如果你只想创建它,从中选择,然后立即再次删除它。根本没有任何意义....