T-SQL的SQL Server查询错误

时间:2022-02-19 12:30:10

I'm getting a my error message as I try to execute the code...

当我尝试执行代码时,我收到了一条错误消息...

The variable x is working properly and showing expected values so are the textBoxes. And connection is open and working as wel because code block before it works fine!

变量x正常工作并显示预期值,因此是textBoxes。并且连接是开放的并且正常工作,因为代码块在它工作正常之前!

string x = ViaClass.name;

SqlConnection connection = new SqlConnection();
SqlCommand command = new SqlCommand(); 
connection.ConnectionString = (@"myconString;Integrated Security=YES");
command.Connection = connection;

try
{
    connection.Open();

    command.CommandText = "IF NOT EXISTS (SELECT 1 FROM ADDRESSES WHERE USID =" + "'" + x + "'" +")" + " INSERT INTO ADDRESSES " + "(AddressLine1, AddressLine2, PostCode) VALUES " + " (@AddressLine1, @AddressLine2, @PostCode)";

    command.Parameters.AddWithValue("@AddressLine1", addressLine1TextBox.Text);
    command.Parameters.AddWithValue("@AddressLine2", addressLine2TextBox.Text);
    command.Parameters.AddWithValue("@PostCode", postCodeTextBox.Text);


    int result = command.ExecuteNonQuery();

    if (result > 0) MessageBox.Show("Record successfully added!");
    else MessageBox.Show("Failed to add record!");
}
catch (SqlException ex) 
{
    MessageBox.Show(ex.Message); 
}
finally
{
    connection.Close();
}

Is there anything wrong with my SQL? I'm using SQL Server and C#

我的SQL有什么问题吗?我正在使用SQL Server和C#

Screenshot for first sql

第一个sql的屏幕截图

T-SQL的SQL Server查询错误

1 个解决方案

#1


1  

If the statement:

如果声明:

 IF NOT EXISTS (SELECT 1 FROM ADDRESSES WHERE USID =" + "'" + x + "'" +")

Is false, then

那是假的

 result = 0

Does your data already exist in the database?

您的数据是否已存在于数据库中?


For a valid statement for this verification do

有关此验证的有效声明,请执行此操作

 command.CommandText = "IF NOT EXISTS (SELECT 1 FROM ADDRESSES WHERE USID =" + "'" + x + "'" +")" + " INSERT INTO ADDRESSES " + "(AddressLine1, AddressLine2, PostCode) VALUES " + " (@AddressLine1, @AddressLine2, @PostCode) ELSE SELECT 1";

But I don't think that having an 'IF' before your update and the checking affect number of rows is a good way for checking if your operation was successful.

但是我认为在更新之前没有'IF'并且检查会影响行数是检查操作是否成功的好方法。

#1


1  

If the statement:

如果声明:

 IF NOT EXISTS (SELECT 1 FROM ADDRESSES WHERE USID =" + "'" + x + "'" +")

Is false, then

那是假的

 result = 0

Does your data already exist in the database?

您的数据是否已存在于数据库中?


For a valid statement for this verification do

有关此验证的有效声明,请执行此操作

 command.CommandText = "IF NOT EXISTS (SELECT 1 FROM ADDRESSES WHERE USID =" + "'" + x + "'" +")" + " INSERT INTO ADDRESSES " + "(AddressLine1, AddressLine2, PostCode) VALUES " + " (@AddressLine1, @AddressLine2, @PostCode) ELSE SELECT 1";

But I don't think that having an 'IF' before your update and the checking affect number of rows is a good way for checking if your operation was successful.

但是我认为在更新之前没有'IF'并且检查会影响行数是检查操作是否成功的好方法。