简体   繁体   中英

Stored Procedure

I have a dataTable which has the column Device Type,DeviceName and label.

There can be multiple Devices for each deviceType. So i want to write the stored procedure which will populate label column as 01,02,03,04.... for each DeviceName and DeviceType Combination.

For Example:-

DeviceName    DeviceType     **Label**

Probe1            1           01
Probe2            1           02
Probe3            1           03
Tank1             2           01
Tank2             2           02
Pump1             3           01
Pump2             3           02  

Have a look at using ROW_NUMBER

SELECT  *,
        ROW_NUMBER() OVER(PARTITION BY DeviceType ORDER BY DeviceName) Label
FROM    Table

EDIT

Here is a little UPDATE example then:

DECLARE @Table TABLE(
        DeviceName VARCHAR(20),
        DeviceType INT,
        Label VARCHAR(20)
)

INSERT INTO @Table SELECT 'Probe1',1,''
INSERT INTO @Table SELECT 'Probe2',1,''
INSERT INTO @Table SELECT 'Probe3',1,''
INSERT INTO @Table SELECT 'Tank1',2,''
INSERT INTO @Table SELECT 'Tank2',2,''
INSERT INTO @Table SELECT 'Pump1',3,''
INSERT INTO @Table SELECT 'Pump2',3,''


;WITH Vals AS (
        SELECT  DeviceName,
                DeviceType,
                ROW_NUMBER() OVER(PARTITION BY DeviceType ORDER BY DeviceName) Label
        FROM    @Table
)
UPDATE  @Table
SET     Label = Vals.Label
FROM    @Table t INNER JOIN
        Vals    ON  t.DeviceName = Vals.DeviceName
                AND t.DeviceType = Vals.DeviceType
SELECT  *
FROM    @Table

With the assumption that DeviceName is unique, you can use ROW_NUMBER like this:

DECLARE @Data TABLE (DeviceName VARCHAR(50), DeviceType INTEGER, Label CHAR(2))
INSERT @Data VALUES ('Probe1', 1, '')
INSERT @Data VALUES ('Probe2', 1, '')
INSERT @Data VALUES ('Probe3', 1, '')
INSERT @Data VALUES ('Tank1', 2, '')
INSERT @Data VALUES ('Tank2', 2, '')
INSERT @Data VALUES ('Pump1', 3, '')
INSERT @Data VALUES ('Pump2', 3, '')

UPDATE d
SET d.Label = RIGHT('0' + CAST(x.RowNo AS VARCHAR(2)), 2)
FROM @Data d
    JOIN (
        SELECT DeviceName, ROW_NUMBER() OVER (PARTITION BY DeviceType ORDER BY DeviceName) AS RowNo
        FROM @Data
    ) x ON d.DeviceName = x.DeviceName

SELECT * FROM @Data

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM