簡體   English   中英

在一個查詢中插入和更新

[英]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)

但是很快意識到這是不可能的。

我想要的是能夠向DiveNrDifficulty添加更多項目到特定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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM