Home > front end >  SQL CONCAT several columns and ALTER TABLE to ADD COLUMN & Having Null Values
SQL CONCAT several columns and ALTER TABLE to ADD COLUMN & Having Null Values

Time:01-05

Im trying to concat 4 or so columns in a SQL Table into a new column in the same SQL Table. I need to Alter the origional table and not create a view. Im using Azure Data Studio, however i have SSMS too

For example here is what my data looks like (currently they are all nvarchar (50) NULL

ColumnA ColumnB ColumnC ColumnD
TEST11 null Cell 1 null
TEST11 555001 Cell 2 S3
TESTZ2 555002 Cell 3 null
TESTZ2 null Cell 4 null
TESTZ2 555003 Cell 5 null

And here is what i want

ColumnA ColumnB ColumnC ColumnD NEWUNIQUEIDCOLUMNNAME
TEST11 null Cell01 null IDTEST11000000Cell0100
TEST11 555001 Cell02 S3 IDTEST11555001Cell02S3
TESTZ2 555002 Cell03 null IDTESTZ2555002Cell0300
TESTZ2 null Cell04 null IDTESTZ2000000Cell0400
TESTZ2 555003 Cell05 null IDTESTZ2555003Cell0500

Ive tried many queries but i just cant get it too work, the following code combines them fine, except if there is null values in one of the columns the unique id column is null,

UPDATE [dbo].TestTable SET NEWUNIQUEIDCOLUMNNAME = ([dbo].TestTable.ColumnA [dbo].TestTable.ColumnB [dbo].TestTable.ColumnC [dbo].TestTable.ColumnD)

It also needs to be able to if its null have a set number of characters in it ie ColumnB if null should be 6x0 ie. 000000 whereas ColumnD needs to only be 2x0 ie 00

Also,

the reason why im doing it this way is because there is no unique ID column that isnt null at some point in the data table that can be referenced and i cannot use a accruing INT as i need to be able to create the unique id in the input app, creating a uniqueIDcolumn this way will work and they will all have unique values as there is no null rows in all of them at once and each rows ID will be different.

UPDATE [dbo].TestTable SET NEWUNIQUEIDCOLUMNNAME = ([dbo].TestTable.ColumnA [dbo].TestTable.ColumnB [dbo].TestTable.ColumnC [dbo].TestTable.ColumnD)

I expected this code to just work. Only been using SQL for 6months.

CodePudding user response:

you can use isnull function to replace null as your expected value, like below:

UPDATE [dbo].TestTable SET NEWUNIQUEIDCOLUMNNAME = ([dbo].TestTable.ColumnA   isnull([dbo].TestTable.ColumnB,'00000')   [dbo].TestTable.ColumnC   isnull([dbo].TestTable.ColumnD,'00')

CodePudding user response:

Initial table is a bad design. However to fix the issue, you can generate an INT sequence to create a unique id in the new column. If not, do you plan to run update statement after each new row, so to generate a unique id for each new row ?

  • Related