試圖創建一個將sql表寫入文件的clr作爲管道分隔符。來自CLR內部的動態sql連接字符串
未測試輸出尚未確定它是否正在嘗試創建連接字符串時遇到障礙。我希望它是動態的,因此它可以根據正在執行的SQL Server來計算連接字符串。
using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Security;
using System.Security.Principal;
using Microsoft.SqlServer.Server;
public partial class CLR_uspExportToFiles
{
[Microsoft.SqlServer.Server.SqlProcedure]
public static void uspExportToFiles(string TableOrQuery, string Delimiter, int Debug, string FilePath, string Filename)
{
var output = FilePath + Filename;
using (System.IO.StreamWriter file = new System.IO.StreamWriter(output))
{
const string DATASOURCE = "Data Source=";
const string INITIALCATALOG = ";Initial Catalog=";
const string INTEGRATEDSECURITY = ";Integrated Security=True;Enlist=false;";
string ConnString;
string InstanceName;
string DbName;
//Establish a connection in the current context to dynamically get the current
//Server and Database Name.
using (SqlConnection sysconn = new SqlConnection("context connection=true"))
{
SqlCommand GetSQLSystemProperties = new SqlCommand();
GetSQLSystemProperties.Connection = sysconn;
sysconn.Open();
//Get the current SQL Server instance name
GetSQLSystemProperties.CommandText = "SELECT @@Servername";
InstanceName = (string)GetSQLSystemProperties.ExecuteScalar();
//Get the current Database Name
GetSQLSystemProperties.CommandText = "SELECT DB_NAME()";
DbName = (string)GetSQLSystemProperties.ExecuteScalar();
sysconn.Close();
//Dynamically construct the connection string to establish a connection outside
//of the current context, so that any error written to the error table won't be
//rolled back.
ConnString = DATASOURCE + InstanceName + INITIALCATALOG + DbName + INTEGRATEDSECURITY;
using (SqlConnection conn = new SqlConnection(ConnString))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM @TableOrQuery", conn))
{
//cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@TableOrQuery", TableOrQuery);
//cmd.Parameters.AddWithValue("@Del", Delimiter);
//cmd.Parameters.AddWithValue("@Debug", Debug);
//cmd.Parameters.AddWithValue("@FilePath", FilePath);
//cmd.Parameters.AddWithValue("@Filename", Filename);
using (SqlDataAdapter sda = new SqlDataAdapter())
{
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
//Build the Text file data.
string txt = string.Empty;
foreach (DataColumn column in dt.Columns)
{
//Add the Header row for Text file.
txt += column.ColumnName + "|";
}
//Add new line.
txt += "\r\n";
file.WriteLine(txt);
foreach (DataRow row in dt.Rows)
{
foreach (DataColumn column in dt.Columns)
{
//Add the Data rows.
txt += row[column.ColumnName].ToString() + "|";
}
//Add new line.
txt += "\r\n";
file.WriteLine(txt);
}
}
}
};
}
}
}
}
}
得到一個錯誤,雖然
Msg 6522, Level 16, State 1, Procedure CLR_uspExportToFiles, Line 0
A .NET Framework error occurred during execution of user-defined routine or aggregate "CLR_uspExportToFiles":
System.Data.SqlClient.SqlException: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)
System.Data.SqlClient.SqlException:
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
at System.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean integratedSecurity, Boolean withFailover, SqlAuthenticationMethod authType)
at System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean withFailover)
at System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString connectionOptions, SqlCredential credential, TimeoutTimer timeout)
at System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer timeout, SqlConnectionString connectionOptions, SqlCredential credential, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance)
at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePa...
和不知道如何解決
上下文連接已經是當前服務器,爲什麼還需要另一個連接? –
'「SELECT * FROM @TableOrQuery」'你不能參數化數據庫對象標識符 –
謝謝,我試着在線構建它的代碼並改變它現在的工作。 也命中該錯誤亞歷克斯感謝,使用(SqlConnection的康恩=新的SqlConnection( 「上下文連接=真」)) { conn.Open()改爲 ; var sqlString = string.Format(「SELECT * FROM {0}」,TableOrQuery); – JQuery