vb.net 检查sql server数据库中是否存在一行,然后使用vb.net删除

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21631195/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 16:42:33  来源:igfitidea点击:

Check if a row exists in sql server database then delete using vb.net

sqlsql-servervb.net

提问by user3284316

Problem:I am currently using a vb application(Visual Studio 2012) to query my database (SQL Server 2012) to check if the row exists in a table if the row does exist then delete it. However if it does not exist then add the row to the database.

问题:我目前正在使用 vb 应用程序 (Visual Studio 2012) 查询我的数据库 (SQL Server 2012) 以检查该行是否存在于表中,如果该行确实存在,则将其删除。但是,如果它不存在,则将该行添加到数据库中。

Additional information:I have text boxes on my vb application with the data. This data is saved to the database.

附加信息:我的 vb 应用程序中有包含数据的文本框。该数据被保存到数据库中。

I have complied the code and cannot seem to find the error in the line of code. Please find the code below!

我已经编译了代码,但似乎无法在代码行中找到错误。请找到下面的代码!

Code:

代码:

cmd2.CommandText = 
 "IF EXISTS(SELECT * FROM(tblLocation) WHERE Tag_ID = '" 
 & txttags.Text 
 & "') THEN (DELETE FROM tblLocation WHERE Tag_ID = '" 
 & txttags.Text 
 & ")' ELSE INSERT INTO tblLocation([Area], [Area_Time], [TagID]) VALUES('" 
 & txtLocation.Text & "' , '" 
 & txtdate.Text & "','" & txttags.Text & "')"

Any help or suggestions would be greatly appreciated!

任何帮助或建议将不胜感激!

采纳答案by wdosanjos

Remove the parenthesis before/after the DELETE statement as follows:

删除 DELETE 语句之前/之后的括号,如下所示:

cmd2.CommandText = 
    "IF EXISTS(SELECT * FROM tblLocation WHERE Tag_ID = '" 
    & txttags.Text 
    & "') DELETE FROM tblLocation WHERE Tag_ID = '" 
    & txttags.Text 
    & "' ELSE INSERT INTO tblLocation([Area], [Area_Time], [TagID]) VALUES('" 
    & txtLocation.Text & "' , '" 
    & txtdate.Text & "','" & txttags.Text & "')"