-1

假设我有一张Name_Address如下表:

CREATE TABLE [dbo].[Name_Address](
[First_Name] [nvarchar] (50)  NULL,
[Last_Name] [nvarchar] (50)  NULL,
[Address] [nvarchar] (50)  NULL,
[City] [nvarchar] (50)  NULL,
[State] [nvarchar] (50)  NULL,
[Zip] [nvarchar] (50)  NULL,
[Phone] [nvarchar] (50)  NULL,
[Cell] [nvarchar] (50)  NULL
) ON [PRIMARY]

SQL中有没有一种方法可以构建一个字符串:

<First Name>John<Last Name>Smith<Address>1233 Your Street<City>Home Town<State>NY<Zip>123456-1234<Phone>111-111-1111<Cell>222-222-222

并将其插入另一个表?

原始帖子未将 xml 标签显示为所需结果的一部分:没有代码格式化,标签被逐字解释并且不显示。

4

3 回答 3

3

您只需使用 将+值连接在一起。

INSERT INTO yourNewTable (newRecord)
SELECT First_Name + Last_Name + Address + City + State + Zip + Phone + Cell
FROM dbo.Name_Address

或添加空格:

INSERT INTO yourNewTable (newRecord)
SELECT First_Name + ' ' + Last_Name + ' ' 
 + Address + ' ' + City + ' ' + State + ' ' + Zip 
 + Phone + ' ' + Cell
FROM dbo.Name_Address

FOR XML PATH如果您想要 XML 格式,也可以使用:

select *
from name_address
for xml path

SQL Fiddle with Demo

或者您可以手动编码 XML 标签,如果您想将完整记录插入到另一个表中,您可以使用:

insert into yourNewTable (yourNewRecord)
select '<FirstName>'+[First_Name] 
  + '<Last_Name>'+[Last_Name] 
  +'<Address>'+[Address] 
  +'<City>'+[City] 
  +'<State>'+[State] 
  +'<Zip>'+[Zip] 
  +'<Phone>'+[Phone] 
  +'<Cell>'+[Cell]
from name_address

参见带有 Select Demo 的 Sql Fiddle

于 2012-09-07T20:55:09.257 回答
0

您可以使用 || 将字段连接在一起:

select First_name||' '||Last_Name||' '+Address . . .
from NameAddress

要插入另一个表,您可以执行以下操作:

insert into AnotherTable
    select '<First Name>'||First_name||'<Last Name>'||Last_Name||'<Address>'+Address . . .
    from NameAddress
于 2012-09-07T20:55:46.137 回答
0
   INSERT INTO MyTable(MyString) 
   SELECT
    '<FirstName>'+[First_Name] + '<Last_Name>'+[Last_Name] +'<Address>'+[Address] +<City>+[City] +<State>+[State] +'<Zip>'+[Zip] +'<Phone>'+[Phone] +'<Cell>'+[Cell] 

    FROM [dbo].[Name_Address]
于 2012-09-07T20:56:14.090 回答