我尝试了很多代码,但没有用。
所以,我需要的是为只有完整名称的表设置一个游标:
create database DB01
use DB01
create table Clients
(
complete_name varchar(50)
)
insert into Clients
values ('Ralph Van Beethoven')
没问题。
现在,我有另一个数据库,其中我必须将我的名字分成“姓名”、“名字”和“第二姓氏”,因此它必须如下所示:
- 姓名:拉尔夫
- 名字:Van
- 第二姓氏:贝多芬
代码:
create database DB02
use DB02
create table Clients_Details
(
Name varchar(50),
First_Last_Name varchar(50),
Second_Last_Name varchar(50)
)
真正的事情来了。我需要一个游标来将 DB01 中的完整名称拆分出来并将其插入到 DB02 中,我有以下代码:
Declare @name as varchar(50)
Declare cClients cursor for Select complete_name from Clients
Declare @temporal table
(
tName varchar(50),
tFLName varchar(50),
tSLName varchar(50)
)
Open cClients
Fetch cClients into @name
While (@@fetch_status = 0 )
Begin
Insert into @temporal
Select
case charindex(' ', @name)
when 0 then @name
else left(@nname, charindex(' ', @name) - 1)
end as tFLName,
case charindex(' ', @name)
when 0 then null
else right(@nname, len(@name) - charindex(' ', @nombre))
end as tSLName
from
Clients
Insert into BD02.dbo.Clients_Details
select tName, tFLName, tSLName
from @temporal
Fetch cClientes into @namecursor
End
Close cClients
Deallocate cClients
它抛出一个错误
The name of the column or the specified column do not match with the definition
所以我猜测我的错误在 charindex
中,因为它只保存了名字和第二个姓氏,但我不太确定现在该怎么做。
有人可以帮助我吗?
最佳答案
首先,您不需要光标来执行此操作
Insert into BD02.dbo.Clients_Details(tName,tFLName,tSLName)
SELECT NAME= Reverse(Parsename(Replace(Reverse(complete_name), ' ', '.'), 1)),
First_Last_Name= Reverse(Parsename(Replace(Reverse(complete_name), ' ', '.'), 2)),
Second_Last_Name= Reverse(Parsename(Replace(Reverse(complete_name), ' ', '.'), 3))
FROM Clients
结果
╔═══════╦═════════════════╦══════════════════╗
║ NAME ║ First_Last_Name ║ Second_Last_Name ║
╠═══════╬═════════════════╬══════════════════╣
║ Ralph ║ Van ║ Beethoven ║
╚═══════╩═════════════════╩══════════════════╝
给你的教授(不推荐)
DECLARE @name AS VARCHAR(50)
DECLARE cClients CURSOR FOR
SELECT complete_name
FROM Clients
OPEN cClients
FETCH cClients INTO @name
WHILE ( @@FETCH_STATUS = 0 )
BEGIN
INSERT INTO Clients_Details
SELECT NAME= Reverse(Parsename(Replace(Reverse(@name), ' ', '.'), 1)),
First_Last_Name= Reverse(Parsename(Replace(Reverse(@name), ' ', '.'), 2)),
Second_Last_Name= Reverse(Parsename(Replace(Reverse(@name), ' ', '.'), 3))
FETCH cClients INTO @name
END
CLOSE cClients
DEALLOCATE cClients
关于sql - SQL Server 中的游标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35608530/