我有一个问题。我已经在堆栈和其他网站上研究过这个问题,但还没有找到答案。我想有一个插入命令,将字符串附加到现有的列名称。我有一个表,在不同月份有多次相同的列。列的示例: name1 为1月, name2 为2月。 地址1 将是1月份,地址2 将是2月份,依此类推。我唯一想到的是如何将变量传递给列的数据,我需要将一个变量添加到已经存在的列名中,所以我不会有多个插入命令。这是我的代码。
If MonthDDL.SelectedValue <> "" Then
Select Case MonthDDL.SelectedValue
Case Is = "January"
Month = "0"
monthVar = "January"
Case Is = "February"
Month = "1"
monthVar = "February"
Case Is = "March"
Month = "2"
monthVar = "March"
Case Is = "April"
Month = "3"
monthVar = "April"
Case Is = "May"
Month = "4"
monthVar = "May"
Case Is = "June"
Month = "5"
monthVar = "June"
Case Is = "July"
Month = "6"
monthVar = "July"
Case Is = "August"
Month = "7"
monthVar = "August"
Case Is = "September"
Month = "8"
monthVar = "September"
Case Is = "October"
Month = "9"
monthVar = "October"
Case Is = "November"
Month = "10"
monthVar = "November"
Case Is = "December"
Month = "11"
monthVar = "December"
'Case Else
End Select
selDate = MonthDDL.SelectedValue
Else
lblSelect.Visible = True
End If
DBCONN.Open()
Dim SqlUpdate = New SqlCommand("SELECT * FROM table WHERE variable = '" + Session("sessionvariable") + "'", DBCONN)
MonthDDL.SelectedValue = monthVar And dr.HasRows = True Then
SqlUpdateCommd = New SqlCommand("UPDATE table SET [table].[name] '"+ Month +'" = '" & contact & "',[table].[address]'"+ Month +'" = '" + address + "' WHERE variable = '" & Session("sessionvariable") & "'", DBCONN)
ElseIf MonthDDL.SelectedValue = monthVar And dr.HasRows = False Then
SqlUpdateCommd = New SqlCommand("INSERT INTO table (name '"+ Month +'", address '"+ Month +'", variable) Values ('" + contact + "', '" + address + "', Session("sessionvariable") + "')", DBCONN)
这是可能的。我甚至接近以正确的方式走这条路。我为语法表示道歉我是vb.net的新手。我甚至不确定要搜索什么可能是为什么我没有真正偶然发现答案。提前谢谢!
答案 0 :(得分:2)
Dwright是对的。你真的不应该这样做,因为,除其他外,如果变量是用户可定义的,它会使你的应用程序容易受到SQL注入攻击。重新设计数据库模式会更好,更简单,这样就不会有像这样的重复列。
但是,代码失败的可能原因是因为您在变量值之前和之后附加了撇号,例如:
"[table].[name '" & variable & "']"
请注意,上述陈述实际上会评估为:
"[table].[name '1']"
但是,你真正想要的,可能就是这样:
"[table].[name1]"
所以,要做到这一点,你需要做这样的事情:
"[table].[name" & variable & "]"
然而,正如我所说,构建这样的动态SQL不仅是一个坏主意,它还表明设计不良的数据库架构。