Convert or Cast VARCHAR to INT; Update column - sql-server

Disclaimer:
I am still learning SQL so I apologize if my question comes off as amateur-ish or is otherwise a very simple answer. I have no formal training. I am teaching myself.
The title may be a bit confusing, as I'm not entirely sure how to word this for a title.
Basically, I want to convert a column in a table thats currently VARCHAR into an INT. The column contains only numbers formatted as such:
00001
00005
02150
These are essentially ID's which will be appended to a Name column later for other purposes. If its necessary to do so, I'd also like to know how to convert the end result INT to VARCHAR for the append portion.
Here's what I have right now:
SELECT CONVERT(INT, LocNo)
It returns the results I expect but I think I need to somehow update the existing LocNo column or otherwise put it in a new column for forward use.
What should I do to achieve this?

Try this
UPDATE TableName
SET LocNo = CONVERT(INT, LocNo)
If you want new column, add new column to table and then do update
ALTER TABLE TableName
ADD NewCol Int Null
UPDATE TableName
SET NewCol = CONVERT(INT, LocNo)
When Selecting and appending to varchar you can do
SELECT CAST(LocNO As VARCHAR) + Name as NameAppended From TableName
If you want 0's back in LocNo/newCol then
SELECT right('00000' + CAST(LocNO As VARCHAR),0) + Name as NameAppended
From TableName

UPDATE YourTable
SET LocNo = CONVERT(INT, LocNo)

Related

Is it possible to start over auto-increment each day, with composite keys: date + int? (MSSQL)

Lets say i have a small db table with only two fields. (MSSQL) Like this:
date (Date) daily_counter (Int)
-------------------------
2021-07-18 0
2021-07-18 1
2021-07-18 2
2021-07-19 0
I want to insert a new fifth row and insert value "2021-07-19" to the date field. And i want to know what the daily_counter is for my new row.
As you perhaps understand by the example, the daily_counter is supposed to auto increase, starting over each day.
So, since there is already a row with that date with the value 0 on the field daily_counter. I want to add 1 to daily_counter for my new row without sending the value 1 to the query.
How can i think when designing this type of table and data. Any hints appreciated. Thanks!
Kr
Gustav
UPDATE:
Ok, i think i got something that could work. The only downside would be when deleting and adding new rows, as the new id could be previosly used and deleted and added again.
A side from that i think i got something that i can use.
It might not be pretty now, but it looks like this.
It seems to work also when there is no row for the current day.
DECLARE #date DATE
SET #date = '2021-07-22'
DECLARE #daily_counter INT
SET #daily_counter = (SELECT MAX(daily_counter) from mytable where date = #date);
SET #daily_counter = #daily_counter + 1;
IF #daily_counter IS NULL
BEGIN
SET #daily_counter = 1;
END
INSERT INTO
mytable
(date, daily_counter)
OUTPUT #daily_counter
VALUES (#date, #daily_counter)
Thanks again for the help!
It's not possible to make the database do this automatically in the row itself. You must have a single counter across all dates (a SEQUENCE would be good for this).
What you can do is use the row_number() function to simulate this at the point where you query the data:
SELECT *, row_number() over (partition by [date] order by [date])
FROM ...
Unfortunately, this will still fail if you need to preserve the original position following deletes, but there's not a good way to do this right now in a database without triggers or application code.

Update data type with case statement

I am trying to update a data type in the table I work with. It currently is stored as an int but it really is a date column.
It looks like 20191012 right now. For some reason instead of using null, they had columns with no dates be 0.
When I query the table I use
case
when bthdat = 0
then '9999-12-31'
else convert(date, convert(varchar(10), bthdat)) as dob
end
Can I use the same logic to update the actual table itself? If so, how? Thanks.
You're not going to be able to UPDATE your existing column, as int and date aren't compatible.
What you can do, however, is change the datatype a couple of times, with an UPDATE in the middle. This, however, assumes that all the values are valid (for example don't have a value like 20190229) and in the ISO format yyyyMMdd
ALTER TABLE dbo.YourTable ALTER COLUMN bthdat varchar(10);
UPDATE dbo.YourTable
SET bthdat = NULL
WHERE bthdat = '0';
ALTER TABLE dbo.YourTable ALTER COLUMN bthdat date;
You can use as follows
update
a
set
bthdat = case
when bthdat = 0 then '9999-12-31'
else convert(date,convert(varchar(10),bthdat))
end
from
YourTable as a
Do not forget to set the else for records that are not updated to keep the existing value.

SQL Server Management Studio decimal column with blank value

I have the couple of columns defined as decimal(16,2).
I would like to leave the value '' (blank) in it.
When I have the select query as
CASE
WHEN FIELD1 IS NULL THEN ''
ELSE FIELD1
END AS FIELD_NAME
This will not allowed as the nature of the column.
Could you please help me how can I put a blank value in this column?
Many thanks
You will either need to leave the values as NULL, which is recommended solution, or convert everything to text. The reason for the error is that you cannot return a decimal and a text value in the same column ('' is a text value).
To convert everything to text and insert the blank value, use the following:
SELECT ISNULL(CONVERT(VARCHAR(20), Field1), '')
FROM myTable
I agree with comments, but if you must do it in SQL you could use a cast in your case statement as per below code. Better handled in front end though as the below code would mean your final select returns a varchar and not a decimal. Handled front end, you can return a decimal from SQL and display blank if NULL.
create table #temp (thing decimal(16,2))
insert into #temp (thing) values(NULL)
select
case when thing IS NULL then ''
else cast(thing as varchar(5)) end
from #temp

Update a part of column value in SQL Server

I have a database in SQL Server with its data. I need change a part of some columns value in some conditions.
Imagine the value as "0010020001".
002 belongs to another value in my database and whenever I want to change it to 005, I must update the previous 10-digits code to "001005001".
Actually, I need to update just a part of columns value using UPDATE statement. How can I do it (in this example)?
While everyone else is correct that if you have control of the schema you should definitely not store your data this way, this is how I would solve the issue you as you described it if I couldn't adjust the schema.
IF OBJECT_ID('tempdb..#test') IS NOT NULL
DROP TABLE #test
create table #test
(
id int,
multivaluecolumn varchar(20)
)
insert #Test
select 1,'001002001'
UNION
select 2,'002004002'
UNION
select 3,'003006003'
GO
declare #oldmiddlevalue char(3)
set #oldmiddlevalue= '002'
declare #newmiddlevalue char(3)
set #newmiddlevalue = '005'
select * from #Test
Update #Test set multivaluecolumn =left(multivaluecolumn,3) + #newmiddlevalue + right(multivaluecolumn,3)
where substring(multivaluecolumn,4,3) = #oldmiddlevalue
select * from #Test
Why dont you use CSV(comma separated values) or use any other symbol like ~ to store tha values. Once you need to update a part of it use php explode function and then update it. After your work is done, concat all the values again to get the desired string to be stored in your column.
In that case your column will have values VARCHAR like 001~002~0001

TSQL Stored Proc to copy records (with a twist!)

I am trying to write a Stored Procedure in SQL Server (2005) to do something that sounds simple, but is actually proving to be more difficult that I thought.
I have a table with 30 columns and 50,000 rows.
The number of records is fixed, but users can edit the fields of existing records.
To save them having to re-key repetitive data, I want to give them the ability to select a record, and specify a range of IDs to copy those details to.
The SP I'm trying to write will take 3 parameters: The source record primary key, and the lower and upper primary keys of the range of records that the data will be copied into.
Obviously the PKs of the destination records remain unchanged.
So I figured the SP needs to do a SELECT - to get all the data to be copied, and an UPDATE - to write the data into the specified destination records.
I just don't know how to store the results of the SELECT to slot them into the UPDATE.
A temp table wouldn't help - selecting from that would be just the same as selecting from the table!
What I need is a variable that is effectively a single record, so I can go something like:
#tempRECORD = SELECT * FROM SOURCETABLE WHERE ID = #sourcePK
UPDATE SOURCETABLE
SET FIELD1 = #tempRECORD.FIELD1,
FIELD2 = #tempRECORD.FIELD2,
...
FIELD30 = #tempRECORD.FIELD30
WHERE ID >= #LOWER_id AND ID <= #UPPER_id
But I don't know how, or if you even can.
I'm also open to any other clever way I haven't even thought of!
Thanks guys!
So I figured the SP needs to do a SELECT - to get all the data to be copied, and an UPDATE - to write the data into the specified destination records.
What you need is the T-SQL-specific extension to UPDATE, UPDATE ... FROM:
UPDATE T
SET
Field1 = source.Field1
, Field2 = source.Field2
, Field3 = source.Field3
FROM
(SELECT * FROM T AS source_T WHERE source_T.ID = #sourcePK) as source
WHERE
T.ID BETWEEN #LOWER_Id AND #UPPER_Id
Note that this ability to put a FROM clause in an UPDATE statement is not standard ANSI SQL, so I don't know how this would be done in other RDBMSs.
I am pretty sure this ain't the easiest way to do it, but it should work without any problems:
DECLARE #tempField1 varchar(255)
DECLARE #tempField2 varchar(255)
...
DECLARE #tempField30 varchar(255)
SELECT #tempField1 = FIELD1, #tempField2 = FIELD2, ... ,#tempField30 = FIELD30 FROM SOURCETABLE WHERE ID = #sourcePK
UPDATE SOURCETABLE
SET FIELD1 = #tempField1,
FIELD2 = #tempField2,
...
FIELD30 = #tempField30
WHERE ID >= #LOWER_id AND ID <= #UPPER_id
You would need to edit the tempField variables so that they have the right type.

Resources