2011-05-09 18 views
4
SqlParameter param = new SqlParameter(); 
param.ParameterName = "@name"; 
param.Value = tableName; 
SqlCommand cmd = new SqlCommand("select * from @name", con); 
cmd.Parameters.Add(param); 
SqlDataReader rd = cmd.ExecuteReader(); 

上面的代碼的結果:問題的下面的錯誤消息中增加參數

必須聲明表變量「@name」。

爲什麼我得到這個錯誤,我該如何解決?

回答

2

錯誤查詢

select * from @name 

請予以更正,之後From表或視圖名稱預期來了,你應該把你的PARAM像'select * from MyTable where col1 = @param'

你不能把@參數,而不是表名。改爲使用String.Format("select * from {0}", "MyTable");

+0

不,我不需要任何條件。我只想獲取給定表中的所有列。 – 2011-05-09 12:11:21

+0

您不能將@param而不是表名。使用String.Format(「select * from {0}」,「MyTable」);代替。 – 2011-05-09 12:13:06

+0

好友,將其標記爲答案,然後如果你發現它真的有幫助。 – 2011-05-09 12:23:05

4

參數化查詢通常處理查詢中的參數 - 不適用於表名稱,列名等。我不相信SQL Server支持參數化表名。

您可能想要將名稱限制爲一組已知的有效表名稱(以避免SQL注入攻擊等),並使用普通字符串替換/格式/任何來構造查詢。

+2

這是正確的。 SQL Server中不能使用參數作爲表名。 – Guffa 2011-05-09 12:06:31

+0

謝謝。我必須寫: – 2011-05-09 12:07:52

+0

SqlCommand cmd = new SqlCommand(「select * from」+ tableName,con);? 或者可能存在更好的方法? – 2011-05-09 12:08:49

1

,而不是在查詢中傳遞的名稱,你可以很容易地取代它在這裏

string s = "select * from " + name; 
SqlCommand cmd = new SqlCommand(s, con); 
SqlDataReader rd = cmd.ExecuteReader(); 

,但這樣會導致SQL注入錯誤

,所以我想建議你去爲dyanmic查詢執行您可以使用的SQL服務器SP_ExecuteSQL

+0

謝謝我寫你怎麼說。我只是想以另一種方式寫它。 – 2011-05-09 12:14:16

+0

你能解釋爲什麼我會得到SQL注入錯誤? – 2011-05-09 12:15:13

+0

@Aram Gevorgyan - 在此查詢名稱值可以更改爲任何可能不被sql服務器查詢接受的事情.........但是去SQ_EXECUTESQL可以輕鬆解決您的問題 – 2011-05-09 12:18:03