我正在尝试组合两个Sql命令,以便我可以使用Select Command中的文本填充数据字段。我希望将文本“Note Goes Here”替换为selectcommand中的数据。但是我不知道该怎么做。
Dim selectCommand As String = "Select Notes from Note Where NoteKey = " & lngNoteKey
strsql = "Insert into Activity (userName,pVisits,timeDate,data,flag)" _ & " Values('" & GetUserName() _ & "', '" & currentPage & "', '" & DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss") & "', '" & "Note Text Goes Here" & "','" & "2" & "')"
我是asp.net和vb和sql的新手,所以要温柔
答案 0 :(得分:1)
一般来说,任何形式的INSERT语句
INSERT (a, b, c)
VALUES ( 'constant', 'constant', X from some table Y where Z)
可以替换为
INSERT (a, b, c)
SELECT 'constant', 'constant', X
FROM Y
WHERE Z
所以你想要一些与此类似的SQL:
INSERT Activity (userName, pVisits, timeDate, data, flag)
SELECT @UserName, @PVisits, GETDATE(), Notes, 2
FROM Note
WHERE NoteKey = @NoteKey
答案 1 :(得分:0)
您可以对同一命令使用多个查询并使用参数来防止sql注入:
Dim connection As New SqlConnection("Data Source=TEst//TEst;Initial Catalog=cMind_ProgramGuide;Persist Security Info=False;")
Dim strsql As String = "Insert into Activity (userName,pVisits,timeDate,data,flag) Select @userName,@pVisits,@timeDate,Notes,@flag from Note Where NoteKey = @note"
Dim Command As New SqlCommand(strsql, connection)
Command.Parameters.Add("@userName", SqlDbType.NVarChar).Value = GetUserName()
Command.Parameters.Add("@pVisits", SqlDbType.NVarChar).Value = currentPage
Command.Parameters.Add("@timeDate", SqlDbType.DateTime).Value = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")
Command.Parameters.Add("@note", SqlDbType.NVarChar).Value = lngNoteKey
Command.Parameters.Add("@flag", SqlDbType.Int).Value = 2
connection.Open()
Command.ExecuteNonQuery()
connection.Close()