我需要为每个人更新一个具有相同编号的SSN字段。因为它们无效而无论哪个SSN都无关紧要,只需要它们用于SSN格式的唯一标识符。这意味着最小或最大数量是可以接受的。当前表包括可以按多列分组的行,以确保每个人都是唯一的,例如名字,姓氏,地址和患者编号。
我如何获取John Doe的EmpID1值并将其复制到每一行,然后对Jane Doe的多行执行相同操作?
谢谢!
答案 0 :(得分:0)
因为它只需要是“SSN格式”,所以我们可以使用row_number
。此外,您的问题是矛盾的,因为您声明需要
create table #testTable (EmpID1 varchar(11) null, LastName2 char(3), FirstName3 char(4))
insert into #testTable
values
(null,'DOE','JOHN'),
(null,'DOE','JOHN'),
(null,'DOE','JOHN'),
(null,'DOE','JOHN'),
(null,'DOE','JOHN'),
(null,'DOE','JOHN')
;with cte as
(select
RN = row_number() over (order by (select null)) + 111111111
, *
from #testTable)
update cte
set EmpID1 = stuff(stuff(RN,4,0,'-'),7,0,'-')
select * from #testTable
drop table #testTable
<强>返回强>
+-------------+-----------+------------+
| EmpID1 | LastName2 | FirstName3 |
+-------------+-----------+------------+
| 111-11-1112 | DOE | JOHN |
| 111-11-1113 | DOE | JOHN |
| 111-11-1114 | DOE | JOHN |
| 111-11-1115 | DOE | JOHN |
| 111-11-1116 | DOE | JOHN |
| 111-11-1117 | DOE | JOHN |
+-------------+-----------+------------+
答案 1 :(得分:0)
您可以尝试以下查询语句。
DECLARE @EmployeeTable TABLE(EmpID1 VARCHAR(20),FirstName VARCHAR(100),LastName VARCHAR(100),PatientNumber INT)
INSERT INTO @EmployeeTable
SELECT '970-42-3783','John','Doe',1 UNION ALL SELECT '971-42-3780','John','Doe',1 UNION ALL SELECT '973-42-4081','John','Doe',1
SELECT * FROM @EmployeeTable
DECLARE @FirstName AS VARCHAR(100)
DECLARE @LastName AS VARCHAR(100)
DECLARE @PatientNumber INT
DECLARE @EmpID1 AS VARCHAR(20)
DECLARE EmployeeCursor CURSOR FOR
SELECT A.FirstName,A.LastName,A.PatientNumber FROM
(SELECT COUNT(*) AS NoOfRow,FirstName,LastName,PatientNumber FROM @EmployeeTable
GROUP BY FirstName,LastName,PatientNumber) A
OPEN EmployeeCursor
FETCH NEXT FROM EmployeeCursor into @FirstName,@LastName,@PatientNumber
WHILE ( @@FETCH_STATUS = 0)
BEGIN
SET @EmpID1 = (SELECT TOP 1 EmpID1 FROM @EmployeeTable WHERE FirstName = @FirstName AND LastName = @LastName AND PatientNumber = @PatientNumber)
UPDATE @EmployeeTable SET EmpID1 = @EmpID1
WHERE FirstName = @FirstName AND LastName = @LastName AND PatientNumber = @PatientNumber
FETCH NEXT FROM EmployeeCursor into @FirstName,@LastName,@PatientNumber
END
CLOSE EmployeeCursor
DEALLOCATE EmployeeCursor
SELECT * FROM @EmployeeTable
以前的数据
EmpID1 FirstName LastName PatientNumber
970-42-3783 John Doe 1
971-42-3780 John Doe 1
973-42-4081 John Doe 1
更新后
EmpID1 FirstName LastName PatientNumber
970-42-3783 John Doe 1
970-42-3783 John Doe 1
970-42-3783 John Doe 1