2017-08-08 57 views
0

我有下面的代碼片段工作得很好填寫表使用SQL存儲過程。我們將SQL從Stored Prcedure更改爲View,並且斷開了該片斷。任何提示如何使用它與視圖,而不是SP?c#代碼片段從數據庫加載表 - 不與視圖工作

using (var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["XXXX"].ConnectionString)) 
      using (var cmd = new SqlCommand("MYVIEW", conn)) 
      using (var adapter = new SqlDataAdapter(cmd)) 
      { 
       //tried CommandType.Text too without success. 
       cmd.CommandType = CommandType.StoredProcedure; 
       adapter.Fill(table); 
      } 

錯誤是:

System.Data.SqlClient.SqlException(0x80131904):爲過程 'MyView的' 請求失敗,因爲 'MyView的' 是一個視圖對象。在System.Data.SqlClient.SqlConnection.OnError(SqlException異常,布爾breakConnection,操作1 wrapCloseInAction) at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) at System.Data.SqlClient.SqlDataReader.TryConsumeMetaData() at System.Data.SqlClient.SqlDataReader.get_MetaData() at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds) at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource 1完成,Int32超時,任務&任務,布爾asyncWrite)在System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior,RunBehavior runBehavior,布爾System.Data.SqlCommand.ExecuteReader(CommandBehavior行爲,字符串方法)上System.Data.SqlCommand.ExecuteDbDataReader(CommandBehavior行爲)上System.Data.Common.DbCommand.System.Data.IDbCommand System.Data.Common.DbDataAdapter.Fill上的System.Data.Common.DbDataAdapter.FillInternal(DataSet數據集,DataTable [] datatables,Int32 startRecord,Int32 maxRecords,String srcTable,IDbCommand命令,CommandBehavior行爲)上的.ExecuteReader(CommandBehavior行爲) (DataTable [] dataTables,Int32 startRecord,Int32 maxRecords,IDbCommand命令,CommandBehavior行爲)在System.Data.Common.DbDataA dapter.Fill(DataTable dataTable)at moodleWCF_test.index.btTurmaIncluir_Click(Object sender,EventArgs e)

謝謝!

回答

2

視圖不能被稱爲存儲過程。使用視圖代替替換下面的行:

使用(VAR CMD =新的SqlCommand( 「SELECT * FROM MyView的」,康涅狄格州))

cmd.CommandType = CommandType.Text;

+0

它工作得很漂亮....謝謝! – user77

+0

FWIW,如果您需要視圖中的所有行,則還可以設置CommandType = CommandType.TableDirect。 IIRC ADO.NET客戶端將爲您添加「select * from」... – JamieS