[SQL Server] assign values to variables in update

Source: Internet
Author: User

-- Create a test environment
If object_id ('tb') is not null drop table TB
Go
Create Table TB
(
Fdate datetime,
Fperiod int,
Fnum int,
Fentryid int
)
Go
Insert Tb (fdate, fperiod, fnum)
Select '2014-1-1 ', 1, 1 Union all
Select '2014-1-1 ', 1, 1 Union all
Select '2014-1-1 ', 1, 1 Union all
Select '2014-1-1 ', 1, 1 Union all
Select '2014-1-3 ', 1, 2 Union all
Select '2014-1-3 ', 1, 2 Union all
Select '2014-1-3 ', 1, 2 Union all
Select '2014-1-4 ', 1, 4 union all
Select '2014-1-4 ', 1, 4
-- Query
-- If update can
Declare @ I int, @ fnum int
Set @ I = 0
Update TB
Set fentryid = @ I,
@ I = case when @ fnum = fnum then @ I + 1 else 0 end,
@ Fnum = fnum
Go
--
Select * from TB
/*
Fdate fperiod fnum fentryid
--------------------------------------------------------
00:00:00. 000 1 1 0
00:00:00. 000 1 1 1
00:00:00. 000 1 1 2
00:00:00. 000 1 1 3
00:00:00. 000 1 2 0
00:00:00. 000 1 2 1
00:00:00. 000 1 2 2
00:00:00. 000 1 4 0
00:00:00. 000 1 4 1

(9 rows affected)

*/

-- If you want to query
-- Because SQL2000 does not have the row_number function, a temporary table is used.
If object_id ('tempdb .. # t') is not null drop table # T
Go
Create Table # T
(
Fdate datetime,
Fperiod int,
Fnum int,
Fentryid int identity
)
Go
Insert # T
Select fdate, fperiod, fnum from TB order by fnum
Go
----
Select fdate, fperiod, fnum,
(Select count (1) from # t where fnum = A. fnum and fentryid <A. fentryid) fentryid
From # T

-- Result
/*
Fdate fperiod fnum fentryid
--------------------------------------------------------
00:00:00. 000 1 1 0
00:00:00. 000 1 1 1
00:00:00. 000 1 1 2
00:00:00. 000 1 1 3
00:00:00. 000 1 2 0
00:00:00. 000 1 2 1
00:00:00. 000 1 2 2
00:00:00. 000 1 4 0
00:00:00. 000 1 4 1

(9 rows affected)

*/

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.