我需要在单个查询中更新和添加信息。
竞争者 - 表
ID Name Age DiveNr Difficulty
|----|-------|----|------------------|-----------|
| 1 | Test | 22 | 000110,011111 | 3,5 |
|____|_______|____|__________________|___________|
目前我一直在尝试使用
INSERT INTO `competitor`(`ID`, `Name`, `Age`, `DiveNr`, `Difficulty`)
VALUES(@idSql,@NameSql,@AgeSql,@DiveNrSql,@DiffSql)
但很快意识到这是不可能的。
我想要的是能够向DiveNr
和Difficulty
添加更多项目到特定ID:
ID Name Age DiveNr Difficulty
|----|-------|----|----------------------|-----------|
| 1 | Test | 22 | 000110,011111,230400 | 3,5,6 |
|____|_______|____|______________________|___________|
这样的东西?
SELECT ID FROM competitor WHERE ID=1;
INSERT INTO competitor(DiveNr,Difficulty)VALUES(@DiveNrSql,@DiffSql)
我将如何做到这一点?
答案 0 :(得分:0)
首先获取该列的旧值: -
declare @oldDiveNrSql varchar(100)
declare @oldDiffSql varchar(100)
set @oldDiveNrSql = (select DiveNr from competitor where ID=@idSql)
set @oldDiffSql = (select Difficulty from competitor where ID=@idSql)
然后使用新值添加旧值: -
declare @newDiveNrSql varchar(100)
declare @newDiffSql varchar(100)
set @newDiveNrSql =@oldDiveNrSql+','+@DiveNrSql
set @newDiffSql =@oldDiffSql','+@DiffSql
最后使用新值更新您的行: -
update competitor set DiveNr=@newDiveNrSql,Difficulty=@newDiffSql
where ID=@idSql