我想将SQL查询导出到SSIS的ExecuteProcessTask中的csv平面文件中。
我看不到带有标题,分隔符的导出并将其限定为文本。 我尝试使用sqlcmd和bcp。
有关信息,我必须使用SELECT *,因为FROM中的视图是变量,因此我必须显示所有列。
使用sqlcmd:
sqlcmd -S ServerName -d dbName -E -Q "SELECT * FROM vPBI_Tasks WHERE [project Leader] like 'ProjectLeaderName'" -o "exportFile.csv" -W -s";"
提取结果:
Scope;Project type;Activity type;OBS;Customer;Contr...
-----;------------;-------------;---;--------;-----...
ESP;ESP - Amendment;NULL;NULL;GSA;ESP_Amendment#13;...
ESP;ESP - Amendment;NULL;NULL;GSA;ESP_Amendment#13;...
ESP;ESP - Amendment;NULL;NULL;GSA;ESP_Amendment#13;...
我想要:
"Scope";"Project type";"Activity type";"OBS";"Customer";"Contra..."
ESP";"ESP - Amendment";"NULL";"NULL";"GSA";"ESP_Amendment#13";""
ESP";"ESP - Amendment";"NULL";"NULL";"GSA";"ESP_Amendment#13";""
ESP";"ESP - Amendment";"NULL";"NULL";"GSA";"ESP_Amendment#13";""
使用bcp:
bcp "SELECT * FROM vPBI_Resources WHERE [project Leader] like 'ProjectLeaderName'" queryout "exportFile.csv" -c -t ; -S ServerName -T
结果:
答案 0 :(得分:0)
我确实已经考虑过这种解决方案,但是我对在行的开头和结尾添加双引号的问题感到困惑。
我找到的解决方法是C#中的脚本。 http://neil037.blogspot.com/2013/07/ssis-script-task-to-export-data-from.html
我在下面放置了C#代码,它将用于其他人:)。
public void Main()
{
String filePath = Dts.Variables["User::temporyExportFilePath"].Value.ToString();
Dts.TaskResult = (int)ScriptResults.Success;
CreateCSVFile(GetTableData(), filePath);
}
public DataTable GetTableData()
{
String sqlQuery = Dts.Variables["User::sqlQuery"].Value.ToString();
String connectionString = Dts.Variables["User::stringDatabaseConnection"].Value.ToString();
SqlConnection connect = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(sqlQuery, connect);
cmd.CommandType = CommandType.Text;
SqlDataAdapter adap = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
adap.Fill(dt);
return dt;
}
public void CreateCSVFile(DataTable dt, string strFilePath)
{
StreamWriter sw = new StreamWriter(strFilePath, false);
int iColCount = dt.Columns.Count;
for (int i = 0; i < iColCount; i++)
{
// Write text qualifier double-quote + value + double-quote
sw.Write("\"" + dt.Columns[i] + "\"");
if (i < iColCount - 1)
{
//Parser
sw.Write(";");
}
}
sw.Write(sw.NewLine);
// Now write all the rows.
foreach (DataRow dr in dt.Rows)
{
for (int i = 0; i < iColCount; i++)
{
if (!Convert.IsDBNull(dr[i]))
{
// Write text qualifier double-quote + value + double-quote
sw.Write("\"" + dr[i].ToString() + "\"");
}
if (i < iColCount - 1)
{
//Parser
sw.Write(";");
}
}
sw.Write(sw.NewLine);
}
//Close file and all data writing
sw.Close();
}