Save SQL query results to a table - sql

I want to save my adjusted query results into a table. For example I have codes 350.8, 351.94 and I have T-SQL code to remove the decimal points resulting in the adjusted results 350,351 etc. I want to save the results into a table, not Excel. Is this possible?
I see you can create a new table but with the same columns, not the new adjusted results. The below doesn't work as SQL Server doesn't recognise adjusted1, 2 and 3.
CREATE TABLE DiagAdj
(
encounter_id NUMERIC,
di_1 INT,
di_2 INT,
di_3 INT,
adjusted1 INT,
adjusted2 INT,
adjusted3 INT,
);
INSERT INTO DiagAdj (encounter_id, adjusted1, adjusted2, adjusted3)
SELECT encounter_id, adjusted1, adjusted2, adjusted3
FROM dbo.Encounters
Decimal places removed. I want to save down adjusted3 results into a table
SELECT
encounter_id, di_3, -- now, try to cast to int the remainder, ending right before the decimal
adjusted3 = TRY_CONVERT(int,LEFT(di_3, COALESCE(NULLIF(CHARINDEX('.', di_3) - 1, -1), 255)))
FROM
dbo.Encounters;

Why don't you just cast each decimal column to integer:
INSERT INTO DiagAdj (encounter_id, adjusted1, adjusted2, adjusted3)
SELECT
encounter_id,
CAST(diag1 AS DECIMAL(10,0)),
CAST(diag2 AS DECIMAL(10,0)),
CAST(diag3 AS DECIMAL(10,0))
FROM dbo.Encounters;

Related

Why do I still get an error when trying to convert varchar to int?

I'm trying to convert this data in my database to int based off the code below from another thread. As I'm pretty new to SQL I just wanted to try and convert the column "Web ID" to understand the code and not have too many errors.
I'm using the following code, but still get an error:
select *
into #tmp
from [db].[desktop-order-data]
truncate table [db].[desktop-order-data]
alter table [db].[desktop-order-data]
alter column ["Web ID)"] int
insert [db].[desktop-order-data]
select cast(["Web ID"] as int)
from #tmp
drop table #tmp
When I run this, I get this error:
Msg 213, Level 16, State 1, Line 4
Column name or number of supplied values does not match table definition.
I'm a bit confused as I'm still referencing the same table as in the query. What should I be referencing here?
You should simply be able to do:
alter table [db].[desktop-order-data] alter column ["Web ID"] int;
For your code, you want an update, not an insert. You don't need a temporary table. Just do:
update [db].[desktop-order-data]
set ["Web ID"] = cast(["Web ID"] as int);
If this causes a problem, then find the rows that don't convert. In SQL Server, you can do:
select d.*
from [db].[desktop-order-data] d
where try_cast(["Web ID"] as int) is null and ["Web ID"] is not null;
If you actually have double quotes around the values, then you need to remove them. I would recommend:
-- remove double quotes
update [db].[desktop-order-data] d
set ["Web ID"] = replace(["Web ID"], '"', '');
-- check that the resulting values are convertible
select *
from db].[desktop-order-data] d
where try_cast(["Web ID"] as int) is null and ["Web ID"] is not null;
-- if the above query returns no rows, then
update [db].[desktop-order-data]
set ["Web ID"] = cast(["Web ID"] as int);
The range for int is:
-2^31 (-2,147,483,648) to 2^31-1 (2,147,483,647)
Your Web ID numbers are 10 digits long and start with 4 - they're not going to fit.
You might try bigint instead.
You can't fit a number on the order of 4363155167 into int, which goes from -2147483648 to 2147483647. Can you use bigint here?
You're getting that error because there is more than one column in [desktop-order-data] and you are trying to insert only 1 column, without specifying the target column.
Just change your insert statement to:
INSERT INTO [db].[desktop-order-data] ([Web ID])
SELECT CAST(["Web ID"] as int)
FROM #tmp

MACRO to create a table in SQL

Hi everyone thanks so much for taking the time to read this.
I'd like to create a macro in Teradata that will create a table from another table based on specific parameters.
My original table consists of three columns patient_id, diagnosis_code and Date_of_birth
......
I'd like to build a macro that would allow me to specify a diagnosis code and it would then build the table consisting of data of all patients with that diagnosis code.
My current code looks like this
Create Macro All_pats (diag char) as (
create table pats as(
select *
from original_table
where diag = :diagnosis_code;)
with data primary index (patid);
I cant seem to get this to work - any tips?
Thanks once again
Your code has a semicolon in a wrong place and a missing closing bracket:
Create Macro All_pats (diag char) as (
create table pats as
(
select *
from original_table
where diag = :diagnosis_code
) with data primary index (patid);
);
Edit:
Passing multiple values as a delimited list is more complicated (unless you use Dynamic SQL in a Stored Procedure):
REPLACE MACRO All_lpats (diagnosis_codes VARCHAR( 1000)) AS
(
CREATE TABLE pats AS
(
SELECT *
FROM original_table AS t
JOIN TABLE (StrTok_Split_To_Table(1, :diagnosis_codes, ',')
RETURNS (outkey INTEGER,
tokennum INTEGER,
token VARCHAR(20) CHARACTER SET Unicode)
) AS dt
ON t.diag = dt.token
) WITH DATA PRIMARY INDEX (patid);
);
EXEC All_lpats('111,112,113');
As the name implies StrTok_Split_To_Table splits a delimited string into a table. You might need to adust the delimiter and the length of the resulting token.

SQL - How to change data type float to nvarchar and remove scientific notation

How do I change the data type float to nvarchar in order to remove the scientific notation and still keep precision? Consider the following:
CREATE TABLE ConversionDataType (ColumnData FLOAT);
INSERT INTO ConversionDataType VALUES (25566685456126);
INSERT INTO ConversionDataType VALUES (12345545546845);
INSERT INTO ConversionDataType VALUES (12345545545257);
When I do a simple read I get the following data, as expected:
select * from ConversionDataType
ColumnData
------------------------------------
25566685456126
12345545546845
12345545545257
Now when I try update the data type to an nvarchar, it gets stored in scientific notation which is something I don't want:
update ConversionDataType
set ColumnData = CAST(ColumnData AS NVARCHAR)
The result set is as follows:
25566700000000
12345500000000
12345500000000
It replaces some digits and adds zeros after the 6th index. How can I go about this? I had a look at the Convert function but that is only for converting date time data types.
Being valid what others said in comment, if you just want to convert float to varchar without scientific notation, you need to convert to numeric. You can try this:
SELECT CAST(CAST(CAST(25566685456126291 AS FLOAT) AS NUMERIC) AS NVARCHAR)
Output:
C1
------------------------------
25566685456126292
Whereas
SELECT CAST(CAST(25566685456126291 AS FLOAT) AS NVARCHAR) AS C1
gives:
C1
------------------------------
2.55667e+016
If you need to change datatype, I think you should add a new column, update it and (if you want) delete the old column and rename the new column at the end.
CREATE TABLE TEST1 (C1 FLOAT)
INSERT INTO TEST1 VALUES (25566685456126291);
ALTER TABLE TEST1 ADD C2 VARCHAR(18)
UPDATE TEST1 SET C2=CAST(CAST(C1 AS NUMERIC) AS VARCHAR)
SELECT * FROM TEST1
Output:
C1 C2
---------------------- ------------------
2.55666854561263E+16 25566685456126292
FLOAT was a very bad decision as this is not a precise data type. If you wanted to store the phone numbers as numbers, you'd have to go for DECIMAL instead.
But you'll have to use NVARCHAR instead. And this is the only reasonable design, as phone numbers can have leading zeros or start with a plus sign. So the first thing is to introduce an NVARCHAR column:
ALTER TABLE ConversionDataType ADD ColumnDataNew NVARCHAR(30);
The function to convert a number into a string in SQL Server is FORMAT. It lets you state the format you want to use for the conversion, which is integer in your case (a simple '0'):
update ConversionDataType set ColumnDataNew = format(ColumnData, '0');
At last remove the old column and then rename the new one with the same name. SQL Server lacks an ALTER TABLE syntax to rename a column, so we must call sp_RENAME instead (at least this is what I have read on the Internet; here is a link to the docs: https://msdn.microsoft.com/de-de/library/ms188351.aspx).
ALTER TABLE ConversionDataType DROP COLUMN ColumnData;
EXEC sp_RENAME 'ConversionDataType.ColumnDataNew', 'ColumnData', 'COLUMN';
Here you can see the results: http://rextester.com/GLLB27702
SELECT CONVERT(NVARCHAR(250), StudentID) FROM TableA
StudentID is your Float Column of database
or Simply use
SELECT CONVERT(NVARCHAR(250), yourFloatVariable)

Bulk insert issue with date from excel into SQL Table

I am trying to bulk insert these two columns from excel into a temp table ##NBP_Table. However, when I do that I get the following error:
'Operand type clash: int is incompatible with date'
Does that mean the date aren't in the format it should be to be inserted into a table?
create table ##NBP_Table
(
Applicable_Date date,
NBP_Value numeric(4,4)
)
insert into ##NBP_Table
values (01/04/2014,1.7107),
(02/04/2014,1.6482),
(03/04/2014,1.686),
(04/04/2014,1.6681)
To get the date insert working, please try this
create table ##NBP_Table
(
Applicable_Date date
NBP_Value numeric(5,4)
)
insert into ##NBP_Table
values ('01/04/2014',1.7107)
The date needs to be in quotation marks
I have also corrected the numeric data type for you
this date in expression is considered as int so it will be performed / operations,
so please use 'before starting date and ' after ending date.
'01-04-2014'
Create table #NBP_Table
(
Applicable_Date date,
NBP_Value numeric(5,4)
)
insert into #NBP_Table
values ('01-04-2014',1.7107),
('02-04-2014',1.6482),
('03-04-2014',1.686),
('04-04-2014',1.6681)

SQL automatically rounding off values

I have two table. First table(Table1) use to get the records and second table(Table2) used to insert first table record into it. But I am little bit confused after getting result.
In table 1 and table 2 column "Amount" have same data type i.e nvarchar(max)
Table1
Id Amount
1 Null
2 -89437.43
2 -533.43
3 22403.88
If I run this query
Insert into Table2(Amount)
Select Amount from Table1
Then get result like this, I don't know why values are automatically rounded off
Table2
Id Amount
1 Null
2 -89437.4
2 -533.43
3 22403.9
SQL Server will round float values when converting back and to from string types.
And then you have the fun bits of empty string being 0, as well other strange effects
SELECT CAST(CAST('' AS float) AS nvarchar(MAX))
SELECT CAST(CAST('0.E0' AS float) AS nvarchar(MAX))
Use decimal.
If you need to store "blank" (how does this differ from NULL?) use a separate bit column to allow that extra value
Here is good explanation about your question.
Eigher you explicitly give float or decimal or numeric(xx,x) (x means numeric value)
Then it will convert as the data, other wise it round off the last value.
Insert into Table2(Amount)
Select cast(Amount as numeric(18,2) --or , cast (Amount as float)
from Table1
Check this link:-
TSQL Round up decimal number
In my case I was doing the conversion to the correct data type but had decimal(18,0) for the column in the table. So make sure the decimal places are represented properly for the column decimal(18,2).
Perhaps it's your query tool that's truncating to 8 characters.
Check the actual fields lengths to see if the problem is really in the database:
SELECT LEN(Amount)
FROM Table2
WHERE Amount LIKE '%-89437.%'
Unreproducible. Running this script on SQL Server 2012:
DECLARE #T1 TABLE ([Amount] nvarchar(max) NULL);
DECLARE #T2 TABLE ([Amount] nvarchar(max) NULL);
INSERT INTO #T1 ([Amount])
VALUES (NULL),('-89437.43'),('-533.43'),('22403.88');
Insert into #T2(Amount)
Select Amount from #T1;
SELECT * FROM #T2;
Produces this result:
Amount
NULL
-89437.43
-533.43
22403.88
The problem you describe does not exist.
This will show you the problem:
DECLARE #T1 TABLE ([Amount123456789] money NULL);
DECLARE #T2 TABLE ([Amount123456789] nvarchar(max) NULL);
INSERT INTO #T1 ([Amount123456789])
VALUES (NULL),('-89437.43123'),('-533.43456'),('22403.88789'),(22403.88789);
Insert into #T2(Amount123456789)
Select Amount123456789 from #T1;
SELECT * FROM #T1;
SELECT * FROM #T2;