在 Vb.net 中使用 IN 子句使用 SQL 将某些内容保存到数据库

发布于 2024-09-25 16:41:31 字数 640 浏览 3 评论 0原文

我的表单上有一个文本框和一个按钮。

我希望运行一个查询(在 Vb.Net 中),该查询将生成带有 IN 值的查询。

下面是我的代码示例,

myConnection = New SqlConnection("Data Source=sqldb\;Initial Catalog=Rec;Integrated Security=True")
myConnection.Open()
myCommand = New SqlCommand("UPDATE dbo.Recordings SET Status = 0 where RecID in ('" & txtRecID.Text & "') ", myConnection)
ra = myCommand.ExecuteNonQuery()
myConnection.Close()
MsgBox("Done!", _
MsgBoxStyle.Information, "Done")

当我输入单个值时,它可以工作,但是当我输入带逗号的值时,它会引发错误:

“将 varchar 值 '1234,4567' 转换为 数据类型 int。”

有人可以帮我解决这个问题或者是否有其他方法?

非常感谢

I have a textbox and a button on a form.

I wish to run a query (in Vb.Net) that will produce a query with the IN Values.

Below is an example of my code

myConnection = New SqlConnection("Data Source=sqldb\;Initial Catalog=Rec;Integrated Security=True")
myConnection.Open()
myCommand = New SqlCommand("UPDATE dbo.Recordings SET Status = 0 where RecID in ('" & txtRecID.Text & "') ", myConnection)
ra = myCommand.ExecuteNonQuery()
myConnection.Close()
MsgBox("Done!", _
MsgBoxStyle.Information, "Done")

When I enter a single value it works but when I enter values with commas it throws an error:

"Conversion failed when converting the varchar value '1234,4567' to
data type int."

Could someone please help me to solve this or if there is an alternative way?

Many Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

伏妖词 2024-10-02 16:41:31

尝试删除将 IN 值括在其中的单引号:

myCommand = New SqlCommand("UPDATE dbo.Recordings SET Status = 0 WHERE RecID IN (" & txtRecID.Text & ") ", myConnection) 

Try removing the single-quotes you're wrapping the IN values in:

myCommand = New SqlCommand("UPDATE dbo.Recordings SET Status = 0 WHERE RecID IN (" & txtRecID.Text & ") ", myConnection) 
缱绻入梦 2024-10-02 16:41:31

如果您正在测试 STRING 变量的多个值,则这些多个值需要用引号引起来。

您的第一次尝试“几乎”成功的原因是您还可以使用引号中的每个单独值生成 SqlCommand。
IE
UPDATE dbo.Recordings SET Status = 0 where RecID IN ('1234', '5678')

在这种情况下,T-SQL 会将每个字符串值隐式转换为 INT,
这就是当你给它“1234, 5678”时它试图做的事情,但这不能被解读为 INT。

If you were testing a STRING variable for multiple values, then those multiple values would need to be in quotes.

The reason your first attempt 'almost' worked was because you could also have generated your SqlCommand with each individual value in quotes.
I.E.
UPDATE dbo.Recordings SET Status = 0 where RecID IN ('1234', '5678')

In that case, T-SQL would have done an implicit conversion of each of the string values to INT,
which is what it was attempting to do when you gave it '1234, 5678' but that isn't decipherable as an INT.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文