目的:
username字段更新改为email字段条件:
用户名是唯一的问题:
执行 update table set usernam=email;用户名重复。username email
---------------------------------
tom [email protected]
[email protected] [email protected]
---------------------------------
期望结果如下
---------------------------------
username email
---------------------------------
[email protected] [email protected]
[email protected] [email protected] 谢谢指教
username字段更新改为email字段条件:
用户名是唯一的问题:
执行 update table set usernam=email;用户名重复。username email
---------------------------------
tom [email protected]
[email protected] [email protected]
---------------------------------
期望结果如下
---------------------------------
username email
---------------------------------
[email protected] [email protected]
[email protected] [email protected] 谢谢指教
你的SQL语句应该可以,
贴记录及要求结果出来看看,记录多一点,以供测试
[email protected] [email protected] ->
[email protected] [email protected] ,
简要说明一下
不可以啊
当更新
tom [email protected]
这条数据的时候
就是把[email protected]作为用户名了
那么数据中已经有
[email protected] [email protected]
这条记录了
就违反唯一约束啦!
所以更新中断了,根本更新不了啊
id email
为方便后面的替换操作,这里的id可以设置成自增长
2、然后将你原来表中的username按照临时表的顺序,将内容替换为临时表的id
3、此时由原来一张表间的数据替换改为两张表间的替换 同时可以以username=id作为条件了麻烦了点 不过应该行的通~~
update table set username = emailUserNaem如果不能为NULL,那就这么写:
update table set username = 'NULL'
update table set username = email思路就是先把username的数据清除掉,然后再填入email的数据进去
主键是uid
即使删除了
username还有唯一约束,
那样可以嘛?
如果你的UserName是主键,就按照这么操作
where b.email is null
union
SELECT a.email as username,a.email from ttk a left join ttk b on a.username=b.email
where b.email is not null
CREATE TABLE tb(uName VARCHAR(10) UNIQUE NONCLUSTERED,mail VARCHAR(10))
GO
--INSERT tb SELECT 1,1 UNION ALL SELECT 1,2
/*
消息 2627,级别 14,状态 1,第 1 行
违反了 UNIQUE KEY 约束 'UQ__tb__212CC0CF'。不能在对象 'dbo.tb' 中插入重复键。
语句已终止。
*/INSERT tb SELECT 1,2
UNION ALL SELECT 2,3
GOSELECT * FROM tb
GO
UPDATE tb SET uName = mail
GO
SELECT * FROM tb
/*
2 2
3 3
*/
GO
DROP TABLE tb
GO
OR
用上述SQL语句生成一个新表
第一步:
你将原表中的email导入其中,多加id一列,变为:
id email
1 [email protected]
2 [email protected]
.....
*************************************************************************
第二步,将原表中的username全部按emailtemp中的email替换为id的值,替换结果如下:
username email
1 [email protected]
2 [email protected]
************************************************************************
第三步:以emailtemp中的id=原表中的username作为条件
将原表中的username替换为emailtemp中的email
此时就得到你想要的结果:
username email
---------------------------------
[email protected] [email protected]
[email protected] [email protected]
你的SQL语句应该可以,
update username set username=email
不过要注意,要进行你所要求的更新,email列必须没有重复值,你检查过没有?
update tb set username=username+'&@#$'
update tb set username=email