输入新行时如何检查和更新现有记录日期,否则添加新行

时间:2019-03-28 14:22:15

标签: vb.net

enter code here Sql表列(Clientid,Client_Status,Notes,Startdt,Enddt,Entrydt,Entryid)我当前的代码从UI添加数据行,用户输入开始日期,状态和注释 Enddt默认为9/9/9999。每当输入新的序号/状态并使用该Clientid检查现有记录/状态时,我都需要将代码更改为-  如果记录存在,则将现有记录的EndDt从9/9/9999更新为从接口输入的StartDt-1(新记录StartDt)。否则输入新客户身份。

Private Sub BtnAddStatus_Click(sender As System.Object, e As System.EventArgs) Handles BtnAddStatus.Click

    Clientid = txtboxClid.Text
    Client_Status = cbboxStatus.Text
    StartDt = txtStartDt.Text
            notes = txtnote.Text


               conn = New SqlClient.SqlConnection("conneting string")
        Dim theQuery As String = "select * from Table name where Clientid = @Clientid and EndDt = '9/9/9999'"
        Dim cmd2 As SqlCommand = New SqlCommand(theQuery, conn)
        cmd2.Parameters.AddWithValue("@Clientid", txtboxClid.Text)

        conn.Open()
        If txtboxClid.Text.Trim <> "" And txtStartDt.Text.Trim <> "" Then
            Using reader As SqlDataReader = cmd2.ExecuteReader()
                If reader.HasRows Then
                    Dim query2 As String = "UPDATETable name SET ([EndDt] = SELECT (todate(StartDt)-1) FROM Table name WHERE Clientid = @Clientid and EndDt ='9/9/9999')"
                    reader.Close()

                End If
            End Using

            Dim query As String = "INSERT INTO Table name (Clientid, Client_Status, Notes, Startdt,Enddt, Entrydt, Entryid) VALUES ('" & Clientid & "','" & Client_Status & "','" & Notes & "','" & StartDt & "',getdate(),'" & UName & "');"
            Dim command = New SqlCommand(query, myconn)
            command.ExecuteNonQuery()

            MsgBox("Status Added ")

            conn.Close()

            Call GetInfoClientid()
    End If
    End If
End Sub

2 个答案:

答案 0 :(得分:1)

一个简单的原因是您没有执行存储在 query2 中的命令,但是您的代码还有其他错误,并且可能会造成灾难性的后果。

首先,您应该始终使用参数,并且永远不要串联字符串来构建sql命令。如果连接字符串,则会启用一个名为Sql Injection的简单技巧,任何人都可以入侵您的数据库。

第二,您可以直接调用更新,而无需检查是否存在先前的相关记录。如果记录不存在,则更新将只返回0记录更改。

最后,应在需要时创建诸如连接之类的一次性物品,并尽快将其丢弃。 using语句用于此目的。

Dim Client_Status As String = cbboxStatus.Text
Dim notes As String = txtnote.Text

' Suppose Clientid is a number not a string
Dim Clientid as Integer = Convert.ToInt32(txtboxClid.Text)

' Suppose you have a date in your database, not a string
Dim StartDt as DateTime = Convert.ToDateTime(txtStartDt.Text)
' Calculate here the previous ending date
Dim PrevEnd As DateTime = StartDt.AddDays(-1)

' Conventional max end date
Dim maxEndDate as DateTime = new DateTime(9999,9,9)

If txtboxClid.Text.Trim <> "" And txtStartDt.Text.Trim <> "" Then

    ' Create here the connection to dispose on exit from the using statement
    Using conn As SqlConnection = New SqlClient.SqlConnection("conneting string")
        conn.Open()
        ' USE PARAMETERS EVERYWHERE. DO NOT USE STRINGS TO FIND A DATE
        Dim query2 As String = "UPDATE [Table name] SET [EndDt] = @newEnd 
                                WHERE Clientid = @Clientid 
                                  AND EndDt = @maxEnd"
        Dim command = New SqlCommand(query2, conn)
        command.Parameters.Add("@Clientid", SqlDbType.Int).Value = Clientid
        command.Parameters.Add("@newEnd", SqlDbType.Date).Value = newEnd
        command.Parameters.Add("@maxEnd", SqlDbType.Date).Value = maxEndDate
        command.ExecuteNonQuery()

        ' Prepare the insert. 
        Dim query As String = "INSERT INTO [Table name] 
              (Clientid, Client_Status, Notes, Startdt,Enddt, Entrydt, Entryid) 
               VALUES 
              (@Clientid, @status,@Notes,@StartDt,@maxDate,getdate(), @UName);"
        command.Parameters.Clear()
        command.Parameters.Add("@Clientid", SqlDbType.Int).Value = Clientid
        command.Parameters.Add("@status", SqlDbType.NVarChar).Value = Client_Status
        command.Parameters.Add("@notes", SqlDbType.NVarChar).Value = notes
        command.Parameters.Add("@startdt", SqlDbType.Date).Value = StartDt
        command.Parameters.Add("@maxDate", SqlDbType.Date).Value = maxEndDate
        command.Parameters.Add("@uname", SqlDbType.NVarChar).Value = uname
        command.CommandText = query
        command.ExecuteNonQuery()
    End Using
    Call GetInfoClientid()
End If

请注意,我传递了我认为是您的列类型的适当类型的参数。认为像“ 9/9/9999”这样的字符串是日期是一个常见的错误。但是对于计算机程序来说,这是一个字符串,如果要用作日期,我们需要将其转换为正确的日期。这种转换通常会导致错误的数据传递到数据库引擎。

答案 1 :(得分:0)

这应该已经在存储过程中处理了。但是,由于您已在此处完成了大部分工作,因此我建议对此进行较小的更改以使其可行。首先,删除更新前的检查,并将更新查询更改为:

Dim query2 As String = "UPDATE Table name SET [EndDt] = todate(@StartDt)-1 WHERE Clientid = @ClientId and EndDt ='9/9/9999'"
Dim cmd As SqlCommand = new SqlCommand(query2, vbConn);
cmd.AddParam(“@StartDt”,StartDt)
cmd.AddParam("@Clientid",ClientId)

(假设clientid为varchar,因为您在insert语句上使用了单引号)

还要为query2编写executenonquery()语句。