VB6如何在字段为空时从结果集中按原样插入表中

时间:2018-12-17 08:06:34

标签: vb6

CREATE TABLE [dbo].[TABLE001]
    (
    [T001_int] [int] NULL,
    [T001_char] [char](100) NULL,
    [T001_decimal] [decimal](5, 0) NULL
    )

CREATE TABLE [dbo].[TABLE002]
    (
    [T002_int] [int] NULL,
    [T002_char] [char](100) NULL,
    [T002_decimal] [decimal](5, 0) NULL
    )

INSERT INTO TABLE002 VALUES (NULL, NULL, NULL)

以上表格定义

    Dim strQuery    As String
    Dim rdoEnv      As rdoEnvironment
    Dim rdoCon      As rdoConnection
    Dim rdoRS       As rdoResultset

    strQuery = ""
    strQuery = strQuery & " SELECT * FROM TABLE002"

    Set rdoEnv = rdoEnvironments(0)
    Set rdoCon = rdoEnv.OpenConnection("", rdDriverNoPrompt, True, MyCon)
    Set rdoRS = rdoCon.OpenResultset(strQuery, rdOpenKeyset, rdConcurReadOnly)

    Do Until rdoRS.EOF = True

        strQuery = ""
        strQuery = strQuery & " INSERT INTO TABLE001"
        strQuery = strQuery & " VALUES"
        strQuery = strQuery & " (" & rdoRS!T002_int & ", '" & rdoRS!T002_char & "'," & rdoRST002_decimal & ")"

        rdoCon.Execute (strQuery)
        rdoRS.MoveNext

    Loop

上面是我的VB6代码

当rdoRS!T002_int = null时,发生错误

当rdoRS!T002_char = null时,插入为

当rdoRS!T002_decimal = null时,发生错误

我想将NULL插入NULL

我该如何解决

请不要告诉我我不应该这样做。

我想知道如何将其插入为空。

1 个答案:

答案 0 :(得分:1)

您可以尝试以下方法:

Dim int_value As String
Dim str_value As String
Dim dec_value As String

int_value = IIf(IsNull(myrs!T002_int), "NULL", CStr(myrs!T002_int))
str_value = IIf(IsNull(myrs!T002_char), "NULL", "'" & myrs!T002_char & "'")
dec_value = IIf(IsNull(myrs!T002_decimal), "NULL", CStr(myrs!T002_decimal))

strQuery = ""
strQuery = strQuery & " INSERT INTO TABLE001"
strQuery = strQuery & " (T001_int, T001_char, T001_decimal)"
strQuery = strQuery & " VALUES"
strQuery = strQuery & " (" & int_value & ", " & str_value & ", " & dec_value & ")"

一些注意事项:

  • 插入时,请始终指定列。
  • 万一T002_char列中包含引号或其他内容时,您会收到错误消息 弄乱了SQL语法。
    最好使用准备好的语句。