2

I have the below column in a table which has same string values. I need to replace the strings which are equal for eg:

+----+-------------+
| ID | Column_Name |
+----+-------------+
|  1 | Imports     |
|  2 | Imports     |
|  3 | Exports     |
|  4 | Exports     |
+----+-------------+

Which needs to be replaced as :

+----+-------------+
| ID | Column_Name |
+----+-------------+
|  1 | Imports1    |
|  2 | Imports2    |
|  3 | Exports1    |
|  4 | Exports2    |
+----+-------------+

Is there a way to achieve this in SQL query ?

The purpose of doing this is that I'm using the 'Column_Name' string values in the dynamic SQL to replace the Integer values because of the same names the different values for the column are not getting replaced.

Itamar Haber
  • 47,336
  • 7
  • 91
  • 117
Gowtham Ramamoorthy
  • 896
  • 4
  • 15
  • 36
  • Can you show an extended sample data set? Is there any order at all to the `ID` numbering scheme and the column name? – Tim Biegeleisen Dec 07 '15 at 05:44
  • No I created a temporary table with ID as(Integer identity)... the column names have the ID values as per the insertion. All I need is the replacement for similar string names with some altenate name or number added to it.... thanks for your comment :) – Gowtham Ramamoorthy Dec 07 '15 at 05:47

2 Answers2

3

You can try this:

UPDATE Your_Table
SET Name = Name + CAST(RN AS varchar(1)) FROM -- varchar(10)
                    (SELECT ROW_NUMBER() OVER(PARTITION BY Name ORDER BY ID) AS RN
                     FROM Your_Table) AS A
Nguyễn Hải Triều
  • 1,454
  • 1
  • 8
  • 14
2

Here is a single which achieves what you want. It performs a union of two inner queries, each of which numbers the Import and Export records from 1, in the order of their original ID values. The outer query selects the ID along with the new Column Name.

SELECT ID, CONCAT([Column Name], NewID)
FROM
(
    SELECT ID, [Column Name],
    ROW_NUMBER() OVER (ORDER BY ID ASC) AS NewID
    FROM your_table
    WHERE [Column Name] = 'Exports'
    UNION ALL
    SELECT ID, [Column Name],
        ROW_NUMBER() OVER (ORDER BY ID ASC) AS NewID
    FROM your_table
    WHERE [Column Name] = 'Imports'
)
ORDER BY ID ASC
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360