0

我的表架构如下:

性别:char(1),not null 姓氏:varchar(25),null 名字:varhcar(35),not null

表中的数据如下所示:

 Gender | Last Name | First Name |

   M       Doe         John
   F       Marie       Jane
   M       Jones       Jameson
   F       Simpson     Alice

我现在正在尝试从 txt 文件中存在的名称更新表中的所有名称。

我的查询如下:

-- Sort out the Forenames we'll be using for the data, we make a #Name2 table because I have yet to figure our
-- inserting specific columns using BULK INSERT and without using a format file.
CREATE TABLE #Name (Name VARCHAR(50))
CREATE TABLE #ForeNames (FirstName VARCHAR(50), Gender VARCHAR(1))
-- Move data in the #Name2 table
BULK INSERT #Name FROM "c:\girlsforenames.txt" WITH (ROWTERMINATOR='\n')
-- Now move it to the forename table and add the gender
INSERT INTO #ForeNames SELECT [Name], 'F' FROM #Name
-- Delete the names from temporary table
TRUNCATE TABLE #Name
-- Same for the boys
BULK INSERT #Name FROM "c:\boysforenames.txt" WITH (ROWTERMINATOR='\n')
INSERT INTO #ForeNames SELECT [Name], 'M' FROM #Name
-- Now do the surnames
TRUNCATE TABLE #Name
BULK INSERT #Name FROM "c:\surnames.txt" WITH (ROWTERMINATOR='\n')


DECLARE @Counter BIGINT
SET @Counter = 4
WHILE (@Counter > 0)
BEGIN
 UPDATE TableName 
 set
 [last_name]= (SELECT TOP 1 FirstName from #ForeNames),
 [first_name]=(SELECT TOP 1 Name FROM #Name ORDER BY NEWID()),
 [gender]= ( SELECT TOP 1 Gender FROM #ForeNames ORDER BY NEWID());
 SET @Counter=@Counter-1
END

DROP TABLE #Name
DROP TABLE #ForeNames

SELECT * FROM TableName

发生的事情是表中的所有行都使用相同的值进行更新,并且每次我执行查询时,它们都会使用新的值集进行更新。

我想要的是遍历每一行并更新它,然后用另一组随机名称更新下一行。但这里它在表的所有行中更新相同的随机名称。

任何帮助,将不胜感激。

4

1 回答 1

2

在您的示例中,每个SELECT语句仅执行一次(因此返回 1 个结果),并且由于您UPDATE不受限制,因此您将相同的值应用于每一行。

如果要使用不同的值更新每一行,可以使用 CTE 和ROW_NUMBER()函数一次更新行。

无需循环,您可以一举完成:

WITH cte AS (SELECT *,ROW_NUMBER() OVER (ORDER BY (SELECT 1)) AS n1
             FROM TableName
            )
UPDATE cte 
SET FirstName = names.Name
FROM cte 
JOIN (SELECT *,ROW_NUMBER() OVER (ORDER BY NEWID()) AS n2
      FROM #name
      )names
    on cte.n1 = names.n2

演示:SQL 小提琴

此示例仅适用于 FirstName。

于 2013-07-08T17:45:28.687 回答