将SQL查询放在带参数的字符串中

时间:2015-10-15 10:45:18

标签: sql vb.net

将长sql查询放到命令有一些问题,但我总是遇到一些问题 - 你可以帮帮我吗?

这是我想要在cmd内添加两个参数newvalueoldvalue

的查询

查询自己:

    UPDATE tbElemPics
    SET    PicturePath = Stuff(PicturePath, Charindex('/', PicturePath, Charindex('/', PicturePath)+1)
                                          + 1, Charindex('/', PicturePath, Charindex('/', PicturePath, Charindex('/', PicturePath)+1)
                                                                          + 1) - Charindex('/', PicturePath, Charindex('/', PicturePath) + 1) - 1, 'newvalue')
    WHERE  Substring(PicturePath, Charindex('/', PicturePath, Charindex('/', PicturePath)+1)
                                 + 1, Charindex('/', PicturePath, Charindex('/', PicturePath, Charindex('/', PicturePath)+1)
                                                                 + 1) - Charindex('/', PicturePath, Charindex('/', PicturePath) + 1) - 1) = 'oldvalue'

使用cmd的方法,上面的sql应放在两个参数中:

 Public Sub ChangeMachineNames(OldMachName As String, NewMachName As String)
        Dim strcon = New AppSettingsReader().GetValue("ConnectionString", GetType(System.String)).ToString()
        Using con As New SqlConnection(strcon)
            Using cmd As New SqlCommand("here i want to put my sql", con)
                cmd.CommandType = CommandType.Text
                cmd.Parameters.AddWithValue("@newvalue", NewMachName)
                cmd.Parameters.AddWithValue("@oldvalue", OldMachName)
                con.Open()
                Dim rowsAffected As Integer = cmd.ExecuteNonQuery()
                con.Close()
            End Using
        End Using
    End Sub

1 个答案:

答案 0 :(得分:1)

只需将其放入变量中,然后将该变量分配给Command

Dim strCmd As String = ""
strCmd &= " UPDATE tbElemPics"
strCmd &= " SET    PicturePath = Stuff(PicturePath, Charindex('/', PicturePath, Charindex('/', PicturePath)+1)"
strCmd &= " + 1, Charindex('/', PicturePath, Charindex('/', PicturePath, Charindex('/', PicturePath)+1)"
strCmd &= " + 1) - Charindex('/', PicturePath, Charindex('/', PicturePath) + 1) - 1, @newvalue)"
strCmd &= " WHERE  Substring(PicturePath, Charindex('/', PicturePath, Charindex('/', PicturePath)+1)"
strCmd &= " + 1, Charindex('/', PicturePath, Charindex('/', PicturePath, Charindex('/', PicturePath)+1)"
strCmd &= " + 1) - Charindex('/', PicturePath, Charindex('/', PicturePath) + 1) - 1) = @oldvalue"


Using cmd As New SqlCommand(strCmd, con)