2015-10-15 66 views
0

将长SQL查询放在命令中有一些问题,但我总是遇到一些问题 - 你能帮我解决吗?将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 
+0

如果你解释你想要产生什么类型的查询,可能你可能会得到更多的答案,可能是解决你的问题的新方法。 – haraman

回答

1

只要将它放入一个变量,然后将该变量分配给命令

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) 
+0

嗨,你确定没有错别字? ^^ – Arie

+1

你怀疑哪里? – haraman

+0

对不起...我更新了我的主帖 - 如何更改你的字符串以传递这两个参数 - 我在查询中标记了它们 – Arie