【问题标题】:How to concat many rows into one string using SQL within VBA / Microsoft Access?如何在 VBA / Microsoft Access 中使用 SQL 将多行合并为一个字符串?
【发布时间】:2013-11-28 06:58:12
【问题描述】:

如何将多行连接成一个字符串?它需要在执行时使用 VBA / Access 和 SQL。

查询:

SELECT name FROM mytable;

结果:

kim
lee
park
cho

我只想:

kim,lee,park,cho

不可能?

【问题讨论】:

  • 您确定要这样做吗?随着你的桌子越来越大,你的绳子会越来越大,最终会断掉。
  • 是的,由于表格的性质,它永远不会变长。

标签: sql vba ms-access concat


【解决方案1】:

使用这个 sql 查询

DECLARE @STR VARCHAR(MAX)
SET @STR=''
SELECT @STR=@STR+ ','+name FROM mytable
SELECT  SUBSTRING(@STR,2,LEN(@STR))

【讨论】:

  • 是的,所以在连接之后,char 确保使用提及 select 语句查询 SELECT SUBSTRING(@STR,2,LEN(@STR))。从第二个位置选择字符串。
【解决方案2】:

试试这个:

-- sql

 create table #user (name varchar(5))

    insert into #user (name) values ('kim')
    insert into #user (name) values ('lee')
    insert into #user (name) values ('park')
    insert into #user (name) values ('cho')

    declare @tmp varchar(50)
    SET @tmp = ''
    select @tmp = @tmp + name + ', ' from #user

-- select @tmp    


    select SUBSTRING(@tmp, 0, LEN(@tmp))

【讨论】:

    【解决方案3】:
    dim rs as recordset
    dim strSQL, output as string
    output = "" 
    'initializing to zero length string, pretty sure it does this by default but 
    'just making sure
    strSQL = "select name from myTable;"
    Set rs = CurrentDb.OpenRecordset(strsql, dbOpenSnapshot)
    'At this point you have the rows
    If Not (rs.EOF And rs.BOF) Then
    rs.MoveFirst
    Do Until rs.EOF = True
    output = output & rs(0) & ","
    rs.MoveNext
    Loop
    

    这应该会为您提供您正在寻找的输出。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-21
      • 2013-08-08
      • 2021-12-12
      • 1970-01-01
      • 2019-12-24
      • 2015-08-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多