2017-08-15 76 views
1

我有一個看起來是這樣的功能...閱讀.csv文件,然後將其插入SQL SERVER - 缺少的東西

Dim iFileNo As Integer 
Dim sLine As String 
Dim sSQL_InsertPrefix As String 
Dim sSQL As String 
Dim vasFields As Variant 
Dim iIndex As Long 


iFileNo = FreeFile 
'Open File 
Open FileName For Input As #iFileNo 

If EOF(iFileNo) Then 
    Exit Sub 
End If 

sSQL_InsertPrefix = "INSERT INTO temptable (Vendor, Invoice, Date1, Date2, HoldPayment, NetRedeemed, GlCode, ServiceName, SepCheck) VALUES (" 

Do Until EOF(iFileNo) 
    Line Input #iFileNo, sLine 

    'Initialize SQL STRING 
    sSQL = sSQL_InsertPrefix 

    vasFields = Split(sLine, " , ") 

    For iIndex = 0 To UBound(vasFields) - 1 
     sSQL = sSQL & "'" 
     sSQL = sSQL & vasFields(iIndex) 
     sSQL = sSQL & "'" 
     sSQL = sSQL & "," 
    Next iIndex 

    sSQL = sSQL & "'" 
    sSQL = sSQL & vasFields(iIndex) 
    sSQL = sSQL & "'" 

    sSQL = sSQL & ")" 

    g_cn.Execute sSQL 
Loop 

Close #iFileNo 

一切看起來不錯,如,文件被打開,我能夠進入該文件,它承認在我的.csv文件中的數據在此行

Line Input #iFileNo, sLine 

然而,當它到達

vasFields = Split(sline," , ") 

VasFie LDS它沒有被拆分

所以當它到達循環:

For iIndex = 0 to Ubound(vasFields) - 1 

它跳過對末端,而是打這部分

sSQL = sSQL & "'" 
    sSQL = sSQL & vasFields(iIndex) 
    sSQL = sSQL & "'" 

    sSQL = sSQL & ")" 

所以整個值插件的一部分聲明,僅在開始和結束時獲取單引號。總體略INSERT語句看起來像這樣..

Insert into temptable (x, y, z) Values ('123,XXX,456') <-- in which case it treats it as a single value aI believe and gives me an error that the number of insert field has to be equal to specified values 

任何想法,爲什麼vasFields =拆分(SLINE的, 「」)沒有得到值是多少?

+1

您確定在逗號分隔符前後有空格嗎?如果不是,我會刪除分割函數的第二個參數中的空格。 –

回答

1

問題是在分割函數的第二個參數中使用的文字。它正在尋找一個空格 - 逗號空間組合。我會拿出空格,並試試這個:

vasFields = Split(sline,",")