简体   繁体   English

通过c#ASP.Net中的网页运行TSQLScripts

[英]Run TSQLScripts via the Web Page in c# ASP.Net

I am trying to build the Web Page which can be used to run the TSQL scripts online. 我正在尝试构建可用于在线运行TSQL脚本的网页。

My DB has so many databases and I am using the System Administrator account to execute these scripts. 我的数据库有很多数据库,我正在使用系统管理员帐户来执行这些脚本。

After building the web page, 建立网页后,

  1. I can run the simple CRUD statements successfully in all databases 我可以在所有数据库中成功运行简单的CRUD语句
  2. I can run the DML statements only for the default connected database, which is MyDB1. 我只能为默认的连接数据库MyDB1运行DML语句。
  3. Whenever, I create the new Object, it sits in the MyDB1. 每当我创建新对象时,它就位于MyDB1中。 But I want to run / create objects in another DB. 但是我想在另一个数据库中运行/创建对象。

I tried to run the following command, which is very simple and it works perfectly in SSMS. 我尝试运行以下命令,该命令非常简单,并且在SSMS中运行良好。

USE MyDB2
GO

CREATE PROCEDURE [dbo].MyProc

AS
BEGIN
    INSERT INTO
        dbo.Table1
        (
        FieldA
        , FieldB
        , FieldC
        )
    VALUES
        (
        'AAA'
        , 'BBB'
        , 'CCC'
        )

END

But I am getting the error message: 但是我收到错误消息:

'CREATE/ALTER PROCEDURE' must be the first statement in a query batch.

My c# code to execute the posted script is here: 我的执行发布脚本的C#代码在这里:

DataTable dt = new DataTable();
            try
            {
                using (SqlConnection cn = new SqlConnection("MyConnString"))
                {
                    cn.Open();
                    SqlCommand cmd = new SqlCommand(sql, cn);

                    using (SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
                    {
                        if (dr.HasRows)
                        {
                            dt.Load(dr);
                        }

                        dr.Close();
                    }

                    cn.Close();
                }
            }
            catch (Exception ex)
            {
                //Log Error
            }

If I removed, USE statement, it was ok, but it created the object in the default DB which is MyDB1. 如果我删除了USE语句,就可以了,但是它在默认数据库MyDB1中创建了对象。 How I can tweak my code to run it in MyDB2? 如何调整代码以在MyDB2中运行它?

USE is an SSMS command, not a SQL statement. USE是SSMS命令,而不是SQL语句。

Change your connect string to specify the appropriate database. 更改您的连接字符串以指定适当的数据库。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM