Microsoft SQL Server - Copy column in table, modify value and type - sql

I'm quite new to scripts and need some help on creating a script doing multiple actions in sequence.
Let's use this tentative (and bisarre) table to illustrate the solution. The table could potentially hold hundreds of entries:
I want to add a PhoneNumber column with varchar type and populate it from the existing PhoneNumber column.
For phone numbers consiting of 5 digits I want to add a leading zero (0) so all entries have the same length (6).
When this is done for all occurances of 5-digit phone numbers I want to delete the old PhoneNumber column
This is how the table should look after step 1:
And after step 2 it should look like this:
Finally, after the third step I want this outcome:
Can this be accomplished with a script? I don't really need the script to follow this exact sequence as long as it results in the desired outcome. This is just the sequence of actions I have thought could be an allright approach.

Here you go
Remember, you can't have 2 columns called the same
ALTER TABLE [TABLENAME] ADD PHONENUMBERCHAR char(6); --Adds a new column
GO;
UPDATE [TABLENAME] SET PHONENUMBERCHAR = RIGHT(CONCAT('000000', PHONENUMBER), 6); --Updates the value
GO;
ALTER TABLE [TABLENAME] DROP COLUMN PHONENUMBER --Deletes the old column

If the value is really an integer, you can use format():
select id, phonenumber, format(phonenumber, '000000')
from t;
You may want to add this as a computed column:
alter table t add phonenumber_6 as (format(phonenumber, '000000'));

Related

How to populate dummy data into an existing table?

I have a large table with given number of rows in which I'd like to replace personal informations with dummy data. I've written functions for this but actually struggling with how to implement it.
I'd like to do something like:
ALTER TABLE SomeTable DROP COLUMN SomeName
ALTER TABLE SomeTable ADD COLUMN SomeName NVARCHAR(30) DEFAULT (SELECT * FROM dbo.FakeName)
Help would be appreciated.
Instead of dropping and adding a column, just do an UPDATE.
If you just want to update the actual data with dummy data , why can't you use update statement as below. We do almost similar in our day to day work. For ex. if we would like to sanitize actual email address of users while restoring the data in my local or test machine (in column SomeName) and in another column we just want to update it with 'XXX' .
UPDATE SomeTable
SET Email_address= SUBSTRING(Email_address,0,CHARINDEX('#',Email_address)) + '#mytest.com',
SomeName2= 'XXX',

Increment number by one using an insert statement SQL

I am trying to manually add records to a SQL table
However in this table we have a column called Trackseq this column determines how the data is viewed on our CMS system.
The highest TrackSeq will appear first.
I want to manually add a new row but i want the code to check based on CLNTID what the current trackSeq is and add one to it. So if the trackseq of the last record was 10 I want the new record to go in with a trackseq of 11.
Here is my code.
INSERT INTO tbl_CommTracking ( CLNTID,
TRACKSEQ,
COMMDATE,
COMMTIME,
PRODCODE,
COMMTYPE,
EMPLOYEEID,
COMMDETAILS,
COMMSTATUS)
VALUES ('0000005566','999',GETDATE(),GETDATE(),'BS','Note','0000000786','Testing a manual import','A')
Thanks
Assuming TRACKSEQ is a numeric format, you can read the actual highest value and store it in a variable to use in your insert statement.
Please note that, in case of high concurrency, you may want to synchronize this execution in order to avoid duplicate #ts values.
As stated by #Tim Biegeleisen above, an IDENTITY column is best suited for this kind of tasks, but keep in mind that it may leave holes in number sequence in case of DELETE and failed INSERTS.
Eg:
DECLARE #ts int; --or whatever numeric datatype it is
SELECT #ts = MAX(TRACKSEQ) + 1 FROM tbl_CommTracking
INSERT INTO tbl_CommTracking (
--...
TRACKSEQ
--..
)
VALUES (
--...
#ts
--...
)
You should probably make TRACKSEQ an auto increment column. First drop your current TRACKSEQ column, then add it back:
ALTER TABLE tbl_CommTrackingDROP COLUMN TRACKSEQ;
ALTER TABLE tbl_CommTracking ADD TRACKSEQ INT IDENTITY;
Note that typically you would also make TRACKSEQ the primary key of the table. If you don't want to, that's OK, but then you'll have to make sure you can generate your own unique values for the CLNTID column.
It isn't entirely clear why you need this; if you just want the latest records, use the date/timestamp column available, which would have been set during insertion.

How to generate auto generated sequence no in sql

I have one requirement. I already have a table named WorkOrder. In this table there is a column Named WorkorderId set as primary key and identity. The next one is voucherNumber. Now I want to generate voucherNumber automatically. The condition is voucher number will not repeat. E.g., first I insert 2 rows into the table and after that I delete the 2nd entry. The next time my voucher number should be 3. Again i insert 3 more entries then after that my voucher no should be 6. Then i delete one row from this table after that my voucher number should be 7. If i delete the last row (I mean 7) then next time the voucher number should the same.
Use IDENTITY(...) when creating the column. This will make a field auto-increment its value.
You'll have to drop the column first in case that it already exists. There is no (clean) way to make this happen on already existing columns.
For further information and examples you can check out http://www.w3schools.com/sql/sql_autoincrement.asp
Edit: Sorry, I have overlooked the info that you are already using IDENTITY(...) on the PK column. Unfortunately SQL-Server can only have a single column with the IDENTITY property per table... So in this case you'll have to make use of a trigger.
This is an example:
CREATE TRIGGER CountRows
ON TestCount
AFTER UPDATE
AS
UPDATE TestCount SET Cnt = Cnt +1 WHERE ID IN (SELECT ID from inserted)
GO
In case you want to enter an IDENTIFIER to the record, it is best to use uniqueIdentifier type column. It is a string constant in the form xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx, in which each x is a hexadecimal digit in the range 0-9 or a-f. For example, 6F9619FF-8B86-D011-B42D-00C04FC964FF is a valid uniqueidentifier value.
On insertion, you can simply proceed as follows;
Insert into MyTable
(WorkorderId, WorkName) values (NewId(), 'Test')
Using this, you can be sure the Id is globally unique.

how to insert a column with value row number in an access table

I have a large access table . I need to have a column which will have value as row number
how can I write an sql query fill an empty column inserted by me with row numbers
Write a sequence for your table . Then have default value as sequence .
So, whenever the column does not get users values , it will take the sequence values.
Im sorry, im a little confused at what you're getting at, but could you not just do an alter table?
ALTER TABLE my_table
ADD row_number int;
Make the Field DataType AutoNumber it will do it for you automatically.

Is there an easy way to add a custom migration script to SQL Compare scripts?

At my work we are currently having some serious pains pushing our database changes across environments. The issue starts to show up when we create a new non-nullable column on an existing table. The script that SQL Compare generates creates the column as non-nullable, so it will always fail. I was hoping that there was some alternative to having to manually edit the script. Is there any way to get around this? If not, how do you guys handle it?
Create a table:
create table #bingo ( id int )
Add a value:
insert into #bingo values (1)
Add a new column:
alter table #bingo add userid int
Populate the new column:
update #bingo set userid = 1 where id = 1
Change the new column to not nullable:
alter table #bingo alter column userid int not null
You would have to manually edit the RedGate Sql Compare to make it work like this.
How do you plan on filling the NOT NULL column? I don't see how SQL Compare could really come up with a solution since it has no way of knowing how you would fill it.
You could create the column with a DEFAULT, then simply add an update statement at the end of the generated scripts to properly update the column if you have some source for the values.
add a default onto the new not null column
when creating a new not null column, what value do all the existing rows get? If you don't know, make the column nullable.