SQL Server Why only one record update in my table sql

qlfbtfca  于 2023-10-15  发布在  其他
关注(0)|答案(3)|浏览(118)

I have following table structure.

| A    | B   | C   | D      | E |
+------+-----+-----+--------+---+
| 1000 |   5 |   2 | 2018-A |   |
| 1001 |  15 |  63 | 2018-A |   |
| 1002 |  25 | 124 | 2018-A |   |
| 1003 |  35 | 185 | 2018-A |   |
| 1004 |  45 | 246 | 2018-A |   |
| 1005 |  55 | 307 | 2018-A |   |
| 1000 |  65 | 368 | 2018-B |   |
| 1001 |  75 | 429 | 2018-B |   |
| 1000 |  85 | 490 | 2018-C |   |
| 1001 |  95 | 551 | 2018-C |   |
| 1002 | 105 | 612 | 2018-C |   |
| 1003 | 115 | 673 | 2018-C |   |
| 1004 | 125 | 734 | 2018-C |   |

I need to update E column by multiplying B*C. In my stored procedure I tried following query, but it only updated the last row:

SELECT @A = a,
       @Ans = b * c
FROM   tbln
WHERE  d = '2018-A'

UPDATE tbln
SET e = @ANS
WHERE d = '2018-A'
  AND a = @A
mtb9vblg

mtb9vblg1#

Problem is your query

SELECT @A = a,
       @Ans = b * c
FROM   tbln
WHERE  d = '2018-A'

only initialise your variables @A and @Ans with one row infos. And only that one is updated afterwards To update all, just use:

UPDATE tbln
SET    e = b*c
WHERE  d = '2018-A'
z4iuyo4d

z4iuyo4d2#

In the first statement you are setting @A = A . Given that column A is the primary key of your table it is uniquely identifying each row. When the first SELECT statement is done executing @A = 1004 .

Then your UPDATE statement executes and is filtering for A = @A which is A = 1004.

If you want to update column E for all rows in the sample then you need to remove your WHERE clause.

dgenwo3n

dgenwo3n3#

SELECT @A = a,

Will only have one value at the end and so you will update only one row

What you need to do is followinf to update all rows with 2018-A

CREATE TABLE tbln
    ([A] int, [B] int, [C] int, [D] varchar(6), [E] int)
;
    
INSERT INTO tbln
    ([A], [B], [C], [D], [E])
VALUES
    (1000, 5, 2, '2018-A', NULL),
    (1001, 15, 63, '2018-A', NULL),
    (1002, 25, 124, '2018-A', NULL),
    (1003, 35, 185, '2018-A', NULL),
    (1004, 45, 246, '2018-A', NULL),
    (1005, 55, 307, '2018-A', NULL),
    (1000, 65, 368, '2018-B', NULL),
    (1001, 75, 429, '2018-B', NULL),
    (1000, 85, 490, '2018-C', NULL),
    (1001, 95, 551, '2018-C', NULL),
    (1002, 105, 612, '2018-C', NULL),
    (1003, 115, 673, '2018-C', NULL),
    (1004, 125, 734, '2018-C', NULL)
;
13 rows affected
UPDATE tbln
SET    e = b*c
WHERE  d = '2018-A'
6 rows affected
SELECT * FROM tbln
ABCDE
1000522018-A10
100115632018-A945
1002251242018-A3100
1003351852018-A6475
1004452462018-A11070
1005553072018-A16885
1000653682018-Bnull
1001754292018-Bnull
1000854902018-Cnull
1001955512018-Cnull
10021056122018-Cnull
10031156732018-Cnull
10041257342018-Cnull

fiddle

相关问题