Ms Sql Convert and insert between 2 databases - sql-server

I have two databases.I insert data from DATABASE_2 TO DATABASE_1 however i need to convert some column.
I must convert Customer_Telephone_Number from varchar to bigint after that insert it.
So,
My Question is in below.
SET IDENTITY_INSERT DATABASE_1.dbo.CUSTOMER_TABLE ON
INSERT INTO DATABASE_1.dbo.CUSTOMER_TABLE
(
Customer_Id,
Customer_Telephone_Number
)
Select
Customer_Id,
Customer_Telephone_Number // This is varchar so i need to convert it to Big int.
from
DATABASE_2.DBO.CUSTOMER_TABLE
Any help will be appreciated.
Thanks.

If the data stored is without spaces or other non numeric symbols:
Select
Customer_Id,
CONVERT(BIGINT,Customer_Telephone_Number)
from
DATABASE_2.DBO.CUSTOMER_TABLE
For instance, if there is value with (222)-3333-333 it would fail. If the value was 2223333333 it would succeed

Related

Inserting a distinct entry into db.table results into implicit conversion error in SQL Server

I have a requirement where I need to insert new entries found in a record into its Master Table and Map the ID of the identifier to the main table
For Instance consider the below example,
-- Insert into Category Master if not exists
INSERT INTO tblCategoryMaster (Category,
CreatedBy,
CreatedDate,
UpdatedBy,
UpdatedDate)
SELECT DISTINCT
(category),
SERVERPROPERTY('MACHINENAME'),
GETDATE(),
SERVERPROPERTY('MACHINENAME'),
GETDATE()
FROM tblTempDataStaging stg
WHERE category IS NOT NULL
AND NOT EXISTS (SELECT 1 FROM tblCategoryMaster ctg WHERE ctg.Category = stg.category);
After executing the select query we get list of distinct entries and every time a new entry is entered in the staging table, the entries are populated in the Master Table accordingly.
Server is not allowing me to insert, its giving me an error saying
Msg 257, Level 16, State 3, Line 39
Implicit conversion from data type sql_variant to nvarchar(max) is not allowed. Use the CONVERT function to run this query.
The data type of the staging table is NVARCHAR(MAX) for the relevant fields except datetime for the date fields
Tried using CONVERT method but I'm unsure on how do we use it with DISTINCT in the picture
Can you suggest how do I resolve this issue?
The error is telling you the problem: SERVERPROPERTY('MACHINENAME') returns the datatype sql_variant:
SELECT system_type_name
FROM sys.dm_exec_describe_first_result_set(N'SELECT SERVERPROPERTY(''MACHINENAME'') AS MachineName',NULL,NULL);
The underlying data type is a nvarchar (thought it certainly won't be 2GB of storage for the name of a machine!) as can be seen here:
SELECT SQL_VARIANT_PROPERTY(SERVERPROPERTY('MACHINENAME'),'Basetype')
You need to explicitly convert the value. For example:
CONVERT(nvarchar(256),SERVERPROPERTY('MACHINENAME'))
I do suggest you change the data type of your column CreatedBy, and I assume UpdatedBy, from nvarchar(MAX) to something like an nvarchar(256); you don't need 2GB of characters (about 1 Billion) to store that information.

save string to a date field in sql server

I have the following string that I need to save to a sql server database column that has a date datatype.
'2017-05-25T00:00:00'
Can I use cast within a insert script to save this value and is this the best way?
yes You can insert the value like this
INSERT INTO YourTable(ColumnName)
SELECT CAST(StringFiled AS DATETIME)
You Can cast it as Date,DateTime or any other Date type you need
You can use any of the following options.
insert into myTable
values (CAST('2017-05-25T00:00:00' as datetime))
insert into myTable
values (Convert(varchar(30),'2017-05-25T00:00:00',102))

SQL INSERT using tables where the columns have different data types and getting error converting

I have two tables and I would like to insert from one into the other. In my staging (source) table every column is defined as nvarchar(300) and this restriction cannot change.
In my destination table, the columns are of all different types. If I want to, for example, select from the source table (data type nvarchar(300)) and insert that column into a data type of decimal(28, 16).
When this happens I get the following error:
Error converting data type nvarchar to numeric.
Even when I use a cast I get the error.
INSERT INTO Destination (
Weighting
)
VALUES (
CAST(src.Weighting AS decimal(28, 16))
)
Could null values be affecting this at all? Is there anything else to consider?
If all data in your staging table column can be implicitly converted to the target data type then you do not have to set up an explicit cast.
But if any one value cannot be converted implicitly (i.e. one cell contains a non-numeric or ill-formatted string value that is supposed to end up in a decimal type column) then the entire transaction will fail.
You can migrate the risk of a failing transaction by setting up the insert like this:
INSERT
LiveTable (
VarcharCol,
DecimalCol,
NonNullableCol
)
SELECT
NvarcharCol1,
CASE ISNUMERIC(nvarcharCol2) = 0 THEN NvarcharColl2 END,
ISNULL(NvarcharCol3, '')
FROM
StagingTable
But clearly that means the risk of losing potentially relevant data or numeric precision.
You can read which data types are implicitly convertible between each other on the MSDN (scroll down to the matrix). For all other conversions you'll have to use CAST or CONVERT.
This will search for non numeric strings
select src.Weighting from src where isnumeric(src.Weighting) = 0
INSERT INTO Destination (Weighting)
SELECT CAST(src.Weighting AS decimal(28, 16))
FROM [Source] src
should work OK, provided your varchar values are in correct format.
If the error still occurs, please give an example of value being converted.
NULLs will successfully convert to NULLs.
TSQL has functions for casting or converting data to the type you want it to be. If your data types in the source are strictly what you are trying to store them as in the destination table and with in the specifications of the destination table you won't have much trouble.
If you have a column of numbers and one of the is 'three' instead of '3' it gets complicated. Here is a question about converting a varchar to a decimal
An example: I can cast 123 as a varchar(20) then cast the varchar into a decimal with no problem when it is appropriate.
SELECT cast(cast('123' as varchar(20)) as decimal(8,2))
However if I try to convert a character it will give an error.
SELECT cast(cast('1a3' as varchar(20)) as decimal(8,2))
The null only be a problem if the target column does not allow nulls, I think the problem is that the format string that can not always be converted into a decimal, see if the decimal separator is a comma instead of a point.

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

"Error converting data type varchar to numeric." - What column?

I have a huge INSERT-statement with 200 columns and suddendly I get the dreaded Error converting data type varchar to numeric. Is there somewhere I can see the actual column that contains the "varchar" value? I know I can remove one of the columns at a time until the error disappears, but it's very tedious.
Unfortunately, this error is a serious pain and there's no easy way to troubleshoot it. When I've encountered it in the past, I've always just had to comment out groups of columns until I find the culprit.
Another approach might be to use the ISNUMERIC() function in in T-SQL to try and find the culprit. Assuming every column in your destination table is numeric (adjust accordingly if it's not), you could try this:
SELECT *
FROM SourceTable
WHERE ISNUMERIC(Column1) = 0
OR ISNUMERIC(Column2) = 0
OR ISNUMERIC(Column3) = 0
OR ISNUMERIC(Column4) = 0
...
This will expose the row that contains your non-numeric value, and should make it pretty clear which column it's in. I know it's tedious, but at least it helps you hunt down the actual value, in addition to the column that's causing trouble.
You don't specify SQL Server Version or number of rows.
For SQL2005+ adding the OUTPUT clause to the INSERT might help identify the rogue row in that it will output the inserted rows until it encounters an error so the next row is the one with the problem
DECLARE #Source TABLE
(
Col1 VARCHAR(10),
Col2 VARCHAR(10)
)
INSERT INTO #Source
SELECT '1','1' UNION ALL
SELECT '2','2' UNION ALL
SELECT '3','3' UNION ALL
SELECT '4A','4' UNION ALL
SELECT '5','5'
DECLARE #Destination TABLE
(
Col1 INT,
Col2 VARCHAR(10)
)
INSERT INTO #Destination
OUTPUT inserted.*
SELECT *
FROM #Source
Returns
(5 row(s) affected)
Col1 Col2
----------- ----------
1 1
2 2
3 3
Msg 245, Level 16, State 1, Line 23
Conversion failed when converting the varchar value '4A' to data type int.
Well, this is just a hunch but what about inserting the data to a temporary table and the using the GUI to migrate the data to the other table? If it still generates an error, you should at least be able to get more feedback on that non-numerical column...
If it doesn't work, consider trying this.
Cheers!

Resources