0

我正在尝试编写一个视图并从该视图中检索数据,我已经这样做了:

 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 中运行它时,它正在运行但没有检索数据

我该怎么办?

4

1 回答 1

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();
} 

但话又说回来:如果你有这样一个简单的选择 - 首先你需要一个视图来做什么,特别是如果你只是想创建它,从中选择,然后立即再次删除它。完全没有任何意义......

于 2012-12-14T06:32:21.963 回答