在SQL [duplicate]中将一列分为两列

时间:2022-09-26 08:00:30

Possible Duplicate:
Splitting one column into two columns in SQL Server CE

可能重复:在SQL Server CE中将一列拆分为两列

I am doing a project with VS2010 using C#.

我正在使用C#与VS2010进行一个项目。

I have a local database (.sdf file). Here is the example content of my database:

我有一个本地数据库(.sdf文件)。以下是我的数据库的示例内容:

Column1

Frodo Baggins
Samwise Gamgee
Peregrin Took
Meriadoc Brandybuck
.
.
.

What I am trying to do is split names and surnames into two different columns, like this:

我想要做的是将名称和姓氏分成两个不同的列,如下所示:

Names                         Surnames

Frodo             Baggins
Samwise           Gamgee
Peregrin          Took
Meriadoc          Brandybuck
.                 .
.                 .
.                 .

Since I'm using SQL Server CE 3.5 Edition, LEFT, MID functions didn't work for me. So, how would I do that?

由于我使用的是SQL Server CE 3.5版,因此LEFT,MID功能对我不起作用。那么,我该怎么做?

1 个解决方案

#1


1  

try this:

DECLARE @YourTable table (Column1  varchar(50))
INSERT @YourTable VALUES ('Frodo Baggins')
INSERT @YourTable VALUES ('Samwise Gamgee')
INSERT @YourTable VALUES ('Peregrin Took')
INSERT @YourTable VALUES ('Meriadoc Brandybuck')
INSERT @YourTable VALUES ('aa')
INSERT @YourTable VALUES ('aa bb cc')

SELECT
    LEFT(Column1,CHARINDEX(' ',Column1)) AS Names
    ,RIGHT(Column1,LEN(Column1)-CHARINDEX(' ',Column1)) AS Surnames
    FROM @YourTable

--both queries produce same output
SELECT 
    SUBSTRING(Column1, 0, CHARINDEX(' ', Column1))
    ,SUBSTRING(Column1, CHARINDEX(' ',Column1) + 1, LEN(Column1)) 
FROM @YourTable

OUTPUT:

Names       Surnames
----------- -------------
Frodo       Baggins
Samwise     Gamgee
Peregrin    Took
Meriadoc    Brandybuck
            aa
aa          bb cc

(6 row(s) affected)

#1


1  

try this:

DECLARE @YourTable table (Column1  varchar(50))
INSERT @YourTable VALUES ('Frodo Baggins')
INSERT @YourTable VALUES ('Samwise Gamgee')
INSERT @YourTable VALUES ('Peregrin Took')
INSERT @YourTable VALUES ('Meriadoc Brandybuck')
INSERT @YourTable VALUES ('aa')
INSERT @YourTable VALUES ('aa bb cc')

SELECT
    LEFT(Column1,CHARINDEX(' ',Column1)) AS Names
    ,RIGHT(Column1,LEN(Column1)-CHARINDEX(' ',Column1)) AS Surnames
    FROM @YourTable

--both queries produce same output
SELECT 
    SUBSTRING(Column1, 0, CHARINDEX(' ', Column1))
    ,SUBSTRING(Column1, CHARINDEX(' ',Column1) + 1, LEN(Column1)) 
FROM @YourTable

OUTPUT:

Names       Surnames
----------- -------------
Frodo       Baggins
Samwise     Gamgee
Peregrin    Took
Meriadoc    Brandybuck
            aa
aa          bb cc

(6 row(s) affected)