Using row.ColumnName on a column with spaces, after a select query generated by C# in WebMatrix

一曲冷凌霜 提交于 2019-12-11 00:55:40

问题


I have compiled a string that queries a database like so:

stringCompiler = "SELECT * FROM SomeTable";

The problem is that some of the columns have spaces in their names (i.e., "City Tag Number").

How can I call this later after I use the db.Query statement. Example:

foreach(var row in db.Query(stringCompiler))
{
    var someVariable = row.Column With Spaces;
}

Obviously the above code would produce an error.

I could go through each column instead of using ' * ', all the while assigning aliases to all of the column names with spaces in them. Example:

stringCompiler = "SELECT \"City Tag Number\" AS CityTagNumber, ...";

But there are a lot of column names in this table and I am assuming there is a better way, and that I just can't find it (I promise, I've looked).

Any help is much appreciated.

----------------EDIT------------------------

I should've specified that I was using SqlServer.


回答1:


In a sql text passed to the DB engine, usually (but it depends on the actual db) you use square brackets (SqlServer, Access) or backticks (mysql)

 stringCompiler = "SELECT [City Tag Number] AS CityTagNumber, ...";

 stringCompiler = "SELECT `City Tag Number` AS CityTagNumber, ...";

while in code (assuming row is a DataRow) you use the name of the column as string

foreach(var row in db.Query(stringCompiler))
{
    var someVariable = row["City Tag Number"].ToString();
}



回答2:


Although the answer by @Steve is a great answer, here's a suggestion that might make your life a bit easier. Go into SQL Server and define a view into the table of interest:

SELECT [City Tag Number] AS CityTagNumber, [Second Field Name] AS SecondFieldName...
FROM  YourTable

Then in your code, use the view instead of directly referencing the table. That way, you only have to do it once, and will make your code more readable and shorter since in the code you won't need all the AS aliases. The view works exactly as if you were going directly to the table. I use this technique and if the table name is YourTable, i call the view vYourTable.



来源:https://stackoverflow.com/questions/13979184/using-row-columnname-on-a-column-with-spaces-after-a-select-query-generated-by

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!