Separate numbers and [] data in a column - sql

I have a data in one of the column looks like this ALAN, DONALD[1234], I need to split this into two columns like Name( ALAN,DONALD), ID (1234)
I tried the following code and I was able to get the ID but not the name
create table #test(NAME_ID VARCHAR(50))
INSERT INTO #TEST VALUES ('ALAN,DONALD [1234])' )
SELECT CAST (substring(NAME_ID,charindex('[',NAME_ID)+1,charindex(']',NAME_ID)-charindex('[',NAME_ID)-1) AS VARCHAR (102) ) AS MRN FROM #TEST

You could do it based on the index of the bracket:
SELECT
RTRIM(SUBSTRING(NAME_ID, 0, CHARINDEX('[',NAME_ID))) AS Name,
CAST (SUBSTRING(NAME_ID,CHARINDEX('[',NAME_ID)+1,CHARINDEX(']',NAME_ID)-
CHARINDEX('[',NAME_ID)-1) AS VARCHAR (102) ) AS MRN
FROM #TEST

Related

Get every string before character in SQL Server

I got two record in table which is as below -:
1.123-21
2.123-21-30
How to query for all string before certain place of character . Below shown expected output
1. 123-21 -> 123
2. 123-21-30 ->123-21
How can I solve it?
DECLARE #T TABLE (Vals VARCHAR(100))
INSERT INTO #T(Vals) VALUES ('123-21') , ('123-21-30')
SELECT LEFT(Vals, LEN(Vals) - CHARINDEX('-', REVERSE(Vals)) )
FROM #T

Save SQL query results to a table

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;

A query that will search for the highest numeric value in a table where the column has an alphanumeric sequence

I have a column (XID) that contains a varchar(20) sequence in the following format: xxxzzzzzz Where X is any letter or a dash and zzzzz is a number.
I want to write a query that will strip the xxx and evaluate and return which is the highest number in the table column.
For example:
aaa1234
bac8123
g-2391
After, I would get the result of 8123
Thanks!
A bit painful in SQL Server, but possible. Here is one method that assumes that only digits appear after the first digit (which you actually specify as being the case):
select max(cast(stuff(col, 1, patindex('%[0-9]%', col) - 1, '') as float))
from t;
Note: if the last four characters are always the number you are looking for, this is probably easier to do with right():
select max(right(col, 4))
Using Numbers table
declare #string varchar(max)
set #string='abc1234'
select top 1 substring(#string,n,len(#string))
from
numbers
where n<=len(#string)
and isnumeric(substring(#string,n,1))=1
order by n
Output:1234
Using PATINDEX you can achieve it, like this -
DECLARE #test table
(
id INT,
player varchar(100)
)
INSERT #test
VALUES (1,'aaa1234'),
(2,'bac8123'),
(3,'g-2391')
SELECT
MAX(CONVERT(INT, LTRIM(SUBSTRING(player, PATINDEX('%[0-9]%', player), LEN(player)))))
FROM #test
Try:
Select MAX(RIGHT(XID,17))
from table
You can also use this method
CREATE TABLE #Tmp
(
XID VARCHAR(20)
)
INSERT INTO #Tmp(XID)
VALUES ('aaa1234'), ('bac8123'), ('g-2391')
SELECT MAX(RIGHT(XID, LEN(XID) - 3))
FROM #Tmp

Varchar to Number in sql

i have written a query in which i am fetching an amount which is a number like '50,000','80,000'.
select Price_amount
from per_prices
As these values contain ',' these are considered to be varchar.Requirement is to to print these as 'number' with ','
that is how can '50,000' be considered as number and not varchar
If a value has anything other than numbers in it, it is not an integer it is string containing characters. in your case you have a string containing character 5, 0 and ,.
If this is what is stored in your database and this is what you want to display then go ahead you do not need to change it to Integer or anything else. But if you are doing some calculations on these values before displaying them, Yes then you need to change them to an Integer values. do the calculation. Change them back to the varchar datatype to show , between thousands and hundred thousands and display/select them.
Example
DECLARE #TABLE TABLE (ID INT, VALUE VARCHAR(100))
INSERT INTO #TABLE VALUES
(1, '100,000'),(2, '200,000'),(3, '300,000'),(4, '400,000'),
(1, '100,000'),(2, '200,000'),(3, '300,000'),(4, '400,000')
SELECT ID, SUM(
CAST(
REPLACE(VALUE, ',','') --<-- Replace , with empty string
AS INT) --<-- Cast as INT
) AS Total --<-- Now SUM up Integer values
FROM #TABLE
GROUP BY ID
SQL Fiddle
you could combine the Replace and cast function
SELECT CAST(REPLACE(Price_amount, ',', '') AS int) AS Price_Number FROM per_prices
for more information visit 'replace', 'cast'
SQLFiddle

How to fully qualify column names in user-defined table types?

I have a bizarre syntax problem when working with user-defined table type (which I'm using in order to pass table-valued parameters to stored procedures).
This is a sample type definition:
CREATE TYPE tvp_Test AS TABLE
(
Column1 int NOT NULL,
Column2 int NOT NULL
)
This is a test table:
DECLARE #Test tvp_Test
INSERT INTO #Test VALUES (10,11)
INSERT INTO #Test VALUES (20,21)
INSERT INTO #Test VALUES (30,31)
These commands work fine:
SELECT * FROM #Test
SELECT Column1 FROM #Test
However, trying to fully qualify a column name gives a syntax error:
SELECT #Test.Column1 FROM #Test -- Doesn't work
Any combination of quotes doesn't seem to help at all:
SELECT #Test.'Column1' FROM #Test -- Doesn't work either
SELECT '#Test'.Column1 FROM #Test -- As above
SELECT '#Test'.'Column1' FROM #Test -- Still no luck
SELECT '#Test.Column1' FROM #Test -- This works but selects the text '#Test.Column1'
This wouldn't seem such a terrible problem... until you start joining tables. Then it becomes a royal pain.
How can I fully qualify column names when working with user-defined table types?
You can alias the table variable like
SELECT A.Column1 FROM #Test A