Sql 从表a中检索数据,将其与其他字段一起插入表B

Sql 从表a中检索数据,将其与其他字段一起插入表B,sql,asp.net,sql-server,vb.net,Sql,Asp.net,Sql Server,Vb.net,我正在尝试组合这两个Sql命令,以便可以使用Select命令中的文本填充数据字段,请参见下文;我想用selectcommand中的数据替换文本“Note Goes Here”。但是我不知道怎么做 Dim selectCommand As String = "Select Notes from Note Where NoteKey = " & lngNoteKey strsql = "Insert into Activity (userName,pVisits,timeDate,data

我正在尝试组合这两个Sql命令,以便可以使用Select命令中的文本填充数据字段,请参见下文;我想用selectcommand中的数据替换文本“Note Goes Here”。但是我不知道怎么做

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,所以请温柔地说,一般来说,任何形式的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

您可以在同一命令上使用多个查询,并使用参数来防止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()

您正在使用哪些数据库管理系统?microsoft sql server?mysql?oracle?Microsoft Sql Server您的代码易受Sql注入攻击。请学习使用参数。无论如何,您可以在一个查询中组合插入/选择。给出了几个简单的例子。@ADyson感谢您的链接并指出了安全问题。我一定会解决这个问题。