2013-11-22 3 views
1

SQL Server 2008 데이터베이스에서 문자열로 저장된 날짜를 smalldatetime으로 변환하려고합니다.SQL Server 2008에서 값을 문자열에서 날짜 형식으로 변환

저장된 문자열의 형식은 16/12/2007 내가 제거 /과로 교체 할 - 내가 생각 다음과 같은 오류

Conversion from string "16/12/2007" to type 'Date' is not valid.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InvalidCastException: Conversion from string "16/12/2007" to type 'Date' is not valid.

Source Error:

Line 34: NewsItem.Visible = True
Line 35: NewsItem.Date_Modified = CDate(GetContent.Ndate)
Line 36: NewsItem.Date_Published = CDate(GetContent.Ndate)

을 받고 16-12-2007

입니다 적절한 날짜 형식을 얻기 위해 / 문자를 -으로 대체하는 함수를 작성한 다음 데이터베이스를 업데이트하지만 시간이 오래 걸립니다.

+1

날짜를 문자열로 저장하지 않으려면 문제가 발생하지 않아야합니다. SQL Server는 완벽하게 사용할 수있는'date' 및'datetime2' 데이터 형식을 가지고 있습니다. ADO.NET은 .NET DateTime 형식과의 변환 방법을 알고 있습니다. 이 설정을 벗어나 부적절한 저장 유형을 사용하는 경우에만 서식 문제가 발생합니다. –

답변

0

데이터베이스에서 날짜를 문자열로 검색 한 다음 Date.ParseExact를 사용하십시오. 날짜 및 시간의 지정된 문자열 표현을 해당 DateTime에 해당하는 것으로 변환합니다.

Dim ydate = "16/12/2007" 
Dim edate As Date = Date.ParseExact(ydate, "dd/MM/yyyy", System.Globalization.DateTimeFormatInfo.InvariantInfo) 
1

실제로 datetime/smalldatetime의를 저장하려면 문자열을 사용하지 마십시오. 지역화/형식 문제를 피하기 위해 sql 매개 변수를 사용하고 SQL 주입을 방지하려면 더 중요한 요소를 사용하십시오. VB.net Datesmalldatetime 열에 사용할 수 있습니다. Date.TryParse을 사용하여 문자열의 유효성을 검사하고 구문을 분석하십시오.

Dim sql = "INSERT INTO dbo.TableName(Date_Modified)VALUES(@Date_Modified);SELECT CAST(SCOPE_IDENTITY() AS INT);" 
Using con = New SqlConnection("Connection-String") 
    Using cmd = New SqlCommand(sql, con) 
     Dim dt As Date 
     If Not Date.TryParse(GetContent.Ndate, dt) Then 
      MessageBox.Show("please enter a valid date") 
      Return 
     End If 
     cmd.Parameters.AddWithValue("@Date_Modified", dt) 
     Dim newID = cmd.ExecuteScalar() ' presuming that you have an identity column that is autoincremented 
    End Using 
End Using 
관련 문제