我是C#和存储过程的初学者,这个应用程序是第一次写的,我想编写一个简单的应用程序来运行我的SQL Server上的存储过程,为了更多解释,我在SQL Server中编写了这个存储过程:
ALTER PROCEDURE [dbo].[CDRCOLLECT]
AS
BEGIN
EXEC xp_cmdshell 'bcp "SELECT "028",rtrim(ltrim(ANUMBER)),rtrim(ltrim(BNUMBER)),rtrim(ltrim(DATE)),rtrim(ltrim(TIME)),rtrim(ltrim(DURATION)) FROM [myTestReport].[dbo].[CDRTABLE]" queryout f:\newOUTPUT.txt -S DESKTOP-A5CFJSH\MSSQLSERVER1 -Uuser -Ppass -f "f:\myFORMAT.fmt" '
print 'run successfully!'
END
并且在C#windows应用程序中使用此代码想要调用该存储过程:
SqlConnection sqlConnection;
try {
sqlConnection = new SqlConnection(conn);
SqlCommand command = new SqlCommand("CDRCOLLECT", sqlConnection);
command.CommandType = CommandType.StoredProcedure;
sqlConnection.Open();
//return command.ExecuteNonQuery();
sqlConnection.Close();
MessageBox.Show("RUN SUCCESSFULL");
}
catch (Exception p)
{
MessageBox.Show(p.ToString());
}
但是这个程序没有运行,发生了什么?我该如何解决?
答案 0 :(得分:3)
对于存储过程中的select命令
sqlConnection = new SqlConnection(conn);
System.Data.SqlClient.SqlDataAdapter SqlDataAdapter1 = new System.Data.SqlClient.SqlDataAdapter("CDRCOLLECT", sqlConnection);
SqlDataAdapter1.SelectCommand.CommandType = System.Data.CommandType.StoredProcedure;
//for add parameter
//SqlDataAdapter1.SelectCommand.Parameters.Add("@param1", System.Data.SqlDbType.NVarChar);
//SqlDataAdapter1.SelectCommand.Parameters["@param1"].Value = DropDownList1.SelectedValue;
System.Data.DataSet DataSet1 = new System.Data.DataSet();
SqlDataAdapter1.Fill(DataSet1 , "0");
if (DataSet1.Tables["0"].Rows.Count > 0)
{
//you can use DataSet1.Tables["0"] for access your output data
}
对于带参数的插入命令,例如
System.Data.SqlClient.SqlCommand scom = new System.Data.SqlClient.SqlCommand("CDRCOLLECT", sqlConnection);
scom.CommandType = System.Data.CommandType.StoredProcedure;
scom.Parameters.Add("@fName", System.Data.SqlDbType.NVarChar);
scom.Parameters.Add("@lName", System.Data.SqlDbType.NVarChar); scom.Parameters["@fName"].Value = TextBox1.Value;
scom.Parameters["@lName"].Value = TextBox2.Value;
scom.ExecuteNonQuery();