LINQ-to-SQL: Why can't I use table name as parameter?
Why this is not possible:
... new DB().ExecuteQuery<String>(@"Select {0} From {1} ", selectParam, tableParam);
This throws thw following exception: Must declare the table variable "@p1".
Thank you
@ before the "" says to compiler that this is a string nothing else
Read it here http://msdn.microsoft.com/en-us/library/362314fe(v=vs.71).aspx
Must declare the table variable "@p0"
seems to be different
Edited
: Dont use table name as a parameter better use your table name only,it will cause sql injection please read
http://en.wikipedia.org/wiki/SQL_injection
I guess the error related somehow to T-SQL Table Variables.
@-quoted string literals start with @ and are enclosed in double quotation marks. For example:
@"good morning" // a string literal
The advantage of @-quoting is that escape sequences are not processed, which makes it easy to write, for example, a fully qualified file name:
@"c:\Docs\Source\a.txt" // rather than "c:\\Docs\\Source\\a.txt"
To include a double quotation mark in an @-quoted string, double it:
@"""Ahoy!"" cried the captain." // "Ahoy!" cried the captain.
Another use of the @ symbol is to use referenced (/reference) identifiers that happen to be C# keywords. For more information, see 2.4.2 Identifiers.
This isn't quite and answer, more a confirmation that it isn't anything to do with @"" strings, but it seems to be a limitation of the Parameter substitution in ExecuteSqlCommand and SqlQuery.
I have the same problem as you and found that you cannot provide the table name as a parameter. I have a command that is of the form:
Context.Database.ExecuteSqlCommand(@"Delete From MyTable WHERE MyColumn = {0}", someValue);
That works fine, but if I try to provide MyTable as a parameter it fails.
If you think about it the table name doesn't really fit as a parameter so it makes sense that it rejects it. However I agree with you that the error message is really not that helpful.
精彩评论