[英]Insert and update in one query
我需要在單個查詢中更新和添加信息。
競爭對手表
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)
我將如何去做呢?
首先獲取該列的舊值:-
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.