使用SqlCommand.ExecuteNonQuery()创建#temp表

问题描述 投票:0回答:1

您好,我正在尝试使用SqlCommand.ExecuteNonQuery创建一个#temp表。当我执行非查询时,不会发生错误,但是也不会创建表。如果我尝试创建普通表,则可以正常工作。如何使用C#的SqlCommand类创建#temp表。

有效查询:

    string createTempTable = $@"CREATE TABLE [dbo].[Holdings](
                                [Fund] [varchar](25) NULL,
                                [PercentFund] [float] NULL,
                                [CommittedCapital] [float] NULL,
                                [DryPowder] [float] NULL,
                                [SDCashBalance] [float] NULL,
                                [PendingTrades] [float] NULL,
                                [PendingCapital] [float] NULL,
                                [MgmtFee] [float] NULL,
                                [AdjustedCash] [float] NULL,
                                [AsOfDate] [datetime] NULL
                            );";
    //SqlCommand cmd = new SqlCommand(createTempTable, conn);
    //cmd.ExecuteNonQuery();

    SQL.NonQuery(createTempTable, dbName, serverName, false, 300);


public static void NonQuery(string query,
                            string databaseName = "MyDataBase",
                            string serverAddress = "MYServerAddress",
                            bool useServiceAcct = false,
                            int commandTimeout = 30)
{
    string connString = GetConnectionString(serverAddress, databaseName, useServiceAcct);
    using (SqlConnection sqlConn = new SqlConnection(connString))
    using (SqlCommand cmd = new SqlCommand(query, sqlConn))
    {
        sqlConn.Open();
        cmd.CommandTimeout = commandTimeout;
        cmd.ExecuteNonQuery();
    }
}

查询似乎不起作用,但没有给出错误:

string createTempTable = $@"CREATE TABLE [dbo].[#Holdings](
                            [Fund] [varchar](25) NULL,
                            [PercentFund] [float] NULL,
                            [CommittedCapital] [float] NULL,
                            [DryPowder] [float] NULL,
                            [SDCashBalance] [float] NULL,
                            [PendingTrades] [float] NULL,
                            [PendingCapital] [float] NULL,
                            [MgmtFee] [float] NULL,
                            [AdjustedCash] [float] NULL,
                            [AsOfDate] [datetime] NULL
                        );";
//SqlCommand cmd = new SqlCommand(createTempTable, conn);
//cmd.ExecuteNonQuery();

SQL.NonQuery(createTempTable, dbName, serverName, false, 300);
c# sql ssms sqlcommand executenonquery
1个回答
0
投票

正如@jonesopolis在评论中指出的那样,当您关闭连接时,表格消失了。如果尝试创建可用于另一个连接的临时表,则可以使用带有双井号的全局临时表:##Holdings。关于这两个很好的讨论:Local vs Global SQL Server Temporary Tables

© www.soinside.com 2019 - 2024. All rights reserved.