2016-08-01 2 views
-1

이것은 아마도 쉬운 일이지만, 나는 단지 100 % 할 방법을 잘 모르겠다 그래서 나는 첫 번째 VB 프로젝트를하고있어, 그래서 사과 다음과 같은 문제 사실 아주 간단합니다.데이터베이스에서 최대 ID 번호를 반환

기본적으로 데이터베이스 테이블을 울트라 그리드에로드 할 때 필자는 필드에 저장된 최대 정수를 검색해야합니다.

이 설명을보다 명확하게하기 위해 데이터베이스의 각 레코드는 고유 한 ID 번호를 가지고 있으므로 각 레코드를 반복하여 가장 높은 ID 번호를 가진 ID를 찾고 ID를 반환해야 사용할 수 있습니다 다른 계산에서.

예를 들어 SQL = SELECT MAX(supportID) FROM tblIncidents을 사용하여이 테이블에 저장된 가장 높은 ID 번호를 검색 할 수 있음을 알고 있습니다.

그래서이 질문의 결과를 변수로 선언하여 변수로 사용하려면 어떻게해야합니까? 먼저 메시지 상자에 표시하여 쿼리가 작동했다는 것을 증명할 수 있습니다. 둘째로 내 코드 전체에서 ID를 사용하는 방법으로 변수를 사용할 수 있습니까?

예; 새 레코드를 tblIncidents 테이블에 저장하는 코드입니다.

Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click 

    Dim incidentSolved As Boolean = False 
    If cboxSolved.Checked Then 
     incidentSolved = True 
    End If 

    If txtClientSave.Text = "" Then 
     MsgBox("Client name cannot be blank") 

    ElseIf rtbProblem.Text = "" Then 
     MsgBox("Problem cannot be blank") 

    ElseIf cboxSolved.Checked = True And rtbSolution.Text = "" Then 
     MsgBox("Please enter solution") 

    Else 
     database.SaveNewIncident(txtClientSave.Text, dtpStart.Value, dtpEnd.Value, rtbProblem.Text, dtpStartTime.Value, dtpEndTime.Value, cboxSolved.Checked, rtbSolution.Text, _con) 

     txtClientSave.Text = "" 
     rtbProblem.Text = "" 
     rtbSolution.Text = "" 
     dtpStart.Value = Date.Today 
     dtpEnd.Value = Date.Today 
     dtpStartTime.Value = DateTime.Now 
     dtpEndTime.Value = DateTime.Now 
     cboxSolved.Checked = False 

    End If 
End Sub 
라고

데이터베이스 기능

Public Shared Function SaveNewIncident(ByVal clientName As String, dateStart As Date, dateEnd As Date, ByVal incidentProblem As String, ByVal timeStart As String, ByVal timeEnd As String, 
             ByVal incidentSolved As Boolean, ByVal incidentSolution As String, _Con As OleDbConnection) 

    Dim tr As OleDbTransaction = Nothing 

    Try 
     tr = _Con.BeginTransaction() 

     Dim Dc As New OleDbCommand 
     Dc.Connection = _Con 

     Dc.CommandType = CommandType.Text 
     Dc.CommandText = "INSERT INTO dbo.tblIncidents VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)" 
     Dc.Transaction = tr 
     Dc.Parameters.Add("@clientName", OleDbType.VarChar).Value = clientName 
     Dc.Parameters.Add("@dateStart", OleDbType.Date).Value = dateStart 
     Dc.Parameters.Add("@dateEnd", OleDbType.Date).Value = dateEnd 
     Dc.Parameters.Add("@incidentProblem", OleDbType.LongVarChar).Value = incidentProblem 
     Dc.Parameters.Add("@timeStart", OleDbType.VarChar).Value = timeStart 
     Dc.Parameters.Add("@timeEnd", OleDbType.VarChar).Value = timeEnd 
     Dc.Parameters.Add("@incidentSolved", OleDbType.Boolean).Value = incidentSolved 
     Dc.Parameters.Add("@incidentSolution", OleDbType.LongVarChar).Value = incidentSolution 

     Dc.ExecuteNonQuery() 

     tr.Commit() 

     MsgBox("Save successful") 

    Catch ex As Exception 

     mdInit.errorLog(ex.Message, ex.StackTrace) 
     MsgBox("Failed to save data, refer to error log") 
     tr.Rollback() 

    End Try 

End Function 
+1

cmd.connection.dispose 

로 마무리? 또한 이러한 유형의 논리는 좋은 접근법이 아닙니다. 한 번 값을 검색하면 다른 사람이 새 값을 삽입하면 어떻게 될까요? –

+0

@SeanLange 안녕하세요,이 응용 프로그램은 한 사람 만 사용하게되므로 삽입 혼란이 발생하지 않습니다. 필자가이 작업을 수행해야하는 이유는 기존 데이터베이스를 새 데이터베이스로 덮어 쓸 수있는 가져 오기 기능을 프로그램에 작성했기 때문입니다. 그러나 SQL Server에서 Identity_Insert를 해제해야합니다. 이제 내 저장 버튼에서 가장 높은 현재 ID를 가져 와서 값을 증가시켜 ID 열로 들어가는 값을 결정해야합니다. –

+1

행을 삽입하고 OUTPUT 절을 사용해야하는 이유는 무엇입니까? 그런 식으로 귀하의 가치가 동일하길 바랄 필요가 없습니다. –

답변

0

당신이 VB.net에서 할 수있는 것은 여기에 부착 된 SQL 연결을 필요로하는 SqlCommand를 정의입니다 - 귀하의 요청에 당신이하는 단일 값을 반환하기 때문에 단일 값의 예를 다음

Dim cmd AS New SqlClient.SQLCommand("SELECT MAX(billID) FROM tblRecurring",connectionString) 

돌아 ExecuteScalar는 그것을 실행할 수

다음

dim x as MaxId = cmd.executeScalar 

당신이 지금까지 시도 무엇 물론

+0

안녕하세요 앤드류, 선 'Dim x As MaxID'가 maxID가 선언되지 않으므로 작동하지 않습니까? –

+0

@joe 그것은'Dim x as Integer = cmd.executeScalar'...이어야합니다. – Codexer

관련 문제