使用vb.net将变量作为字段名sql

时间:2015-05-25 02:03:54

标签: vb.net postgresql

有了这些数据:

id | month    | 2015 | 2014 | 2013
1  | january  | 2    | 4    | 6  
2  | february | 10   | 12   | 14
3  | march    | 16   | 18   | 20

我这里有vb.net代码

Dim asd As Double = 2015
Dim msg As Double

sql = "select " & asd & " from tbl_coll_penalty where month = 'february'"
sda = New NpgsqlDataAdapter(sql, pgConnection)
sda.Fill(DS, "t")

msg = DS.Tables("t").Rows(0)(0).ToString()
MessageBox.Show(msg)

我对此代码的回答错误,因为此代码的答案是" 2015"但我希望答案是" 10"。有人可以帮我正确的代码吗?

1 个答案:

答案 0 :(得分:0)

在PostgreSQL中,您的专栏名称" 2015"被解释为文字值。所以当你提交查询时:

SELECT 2015 FROM tbl_coll_penalty ...

你只需获得2015年的价值。

在SQL标准中,列标识符不能以数字(0..9)开头。查看文档here。让PostgreSQL解释字符串" 2015"作为列名,您应该引用它:

sql = "select """ & asd & """ from tbl_coll_penalty where month = 'february'"