Format sql column when using select - sql

I have the following query to select record but i wan to format the column on the result set.
SELECT
COALESCE(dbo.tblMitchellLandscapeID.PatchSize,0) as PatchSize,
dbo.tblMitchellLandscape.MitchellLandscapeName
FROM tblMitchellLandscapeID
INNER JOIN dbo.tblMitchellLandscape
ON dbo.tblMitchellLandscapeID.MitchellLandscapeID=dbo.tblMitchellLandscape.MitchellLandscapeID
WHERE AssessmentVersionID = #AssessmentVersionID
"PatchSize" is a decimal value so it stored always like two decimals "15.10". All i trying to format to one decimal when the select statement is executed i wan to populate the result set like "15.1" rather than 15.10.

You can just cast it to the format you want:
SELECT CAST(COALESCE(li.PatchSize, 0) as decimal(5, 1)) as PatchSize,
l.MitchellLandscapeName
FROM tblMitchellLandscapeID li INNER JOIN
dbo.tblMitchellLandscape l
ON li.MitchellLandscapeID = l.MitchellLandscapeID
WHERE AssessmentVersionID = #AssessmentVersionID;
Notice the query is also easier to read (and write) if you use table aliases.

Related

Error while converting varchar to Decimal

In my table I have a column(Varchar). It contains values like 'abc^1234567^xyz'.
I need to select part of the value and convert it to select the number and convert it to a decimal number and compare this number to a number from another table by joining two tables.
So far I get error while want to convert it from varchar to decimal.
Here is my error message:
Msg 8114, Level 16, State 5, Line 1
Error converting data type varchar to numeric.
Here is my code:
SELECT
a.Status,
Cast(SUBSTRING(sourceNatKey, LEN(sourceNatKey)-11,7) As Decimal(18,4)),
b.caseId
FROM AGREEMENT_STATUS a
INNER JOIN APPLICATION_FACT b
ON
Cast(SUBSTRING(sourceNatKey, LEN(sourceNatKey)-11,7) As decimal(18,4)) =
b.caseId
You could use the LIKE operator in the JOIN for such situations.
But if you really have to get a substring from such string ('abc^1234567^xyz'), you could use such construction:
SELECT
a.Status,
Cast(SUBSTRING(sourceNatKey, CHARINDEX('^',sourceNatKey) + 1,CHARINDEX('^',sourceNatKey, CHARINDEX('^',sourceNatKey)+1) - CHARINDEX('^',sourceNatKey) - 1) As decimal(18,4)),
b.caseId
FROM AGREEMENT_STATUS a
INNER JOIN APPLICATION_FACT b
ON
Cast(SUBSTRING(sourceNatKey, CHARINDEX('^',sourceNatKey) + 1,CHARINDEX('^',sourceNatKey, CHARINDEX('^',sourceNatKey)+1) - CHARINDEX('^',sourceNatKey) - 1) As decimal(18,4)) =
b.caseID
You could do this the other way:
SELECT
a.Status,
b.caseId
FROM AGREEMENT_STATUS a JOIN
APPLICATION_FACT af
ON sourceNatKey LIKE '%^' + CAST(b.caseID as varchar(255)) + '^%'
The caseId column has the information in your second column, so that doesn't need to be repeated.
The code SUBSTRING(sourceNatKey, LEN(sourceNatKey)-11,7) will result in ^123456 given the value abc^1234567^xyz. This fails because ^ is non-numeric. Change the offset value from the LEN call to be -10 in order to only retrieve the numeric part of your string.
For further information regarding SUBSTRING, see SUBSTRING (Transact-SQL) Documentation.

How can I select a row having a BigInt and a DateTime field starting with a specigic value?

I am working on a Microsoft SQL Server database and I have the following problem to implement these 2 simple select query.
So I have a table named MyTable that has a column OtherFieldFK of type BigInt with a value of 70016592107.
So for example I want search all the record in this table that have the OtherFieldFK starting with the value 70.
I tried to use like in this way:
select *
from MyTable
where OtherFieldFK like = '70%'
but it doesn't work. I think that like clause works only on string, is it right?
In this table I also have a DATETIME column named DataInizioGestione.
I tried to do the same thing:
select *
from DataInizioGestione
where OtherFieldFK like = '2016%'
but in this case it doesn't work either.
How can I correctly implement these 2 queries?
the first should be right, as you wrote:
select * from MyTable where OtherFieldFK like = '70%'
for the second should be converted to the date format in the nvarchar (es 121 with this format aaaa-mm-gg hh:mi:ss.mmm(24h)); in this way you can make the comparison with the like:
select * from MyTable where convert(nvarchar,DataInizioGestione,121) like = '2016%'
or you can directly compare the year:
select * from MyTable where year(DataInizioGestione) = 2016

db2 query returning 0 records

I am trying to execute below query:
select * from trgdms.src_stm where trim(src_stm_code) in (select concat (concat('''', trim(replace(processed_src_sys_cd,',',''','''))),'''' ) from trgdms.batch_run_log where src_stm_cd_or_hub_cd='CTR' and file_process_dt='2015-06-19' and batch_id=42);
the src_stm_code column of table trgdms.src_stm have values like T19,T68,T73 etc. When I run the inner query alone i do get the correct result:
select concat (concat('''', trim(replace(processed_src_sys_cd,',',''','''))),'''' ) from trgdms.batch_run_log where src_stm_cd_or_hub_cd='CTR' and file_process_dt='2015-06-19' and batch_id=42
Result: 'T19','T68','T73'
Wondered if anyone has used something similar in db2?
Remove the concat part from the inner query. When you concatenate values, the list of values generated will be treated as a string and the query doesn't return any results.
select * from trgdms.src_stm where trim(src_stm_code)
in (select trim(replace(processed_src_sys_cd,',',''',''')) from trgdms.batch_run_log
where src_stm_cd_or_hub_cd='CTR' and file_process_dt='2015-06-19' and batch_id=42);

I need to remove leading zeros after a decimal point

this is my first time posting here and I am a basic SQL user and need help.
I have a varchar column that stores data like below:
Year.Docid
2007.000000001
2007.000000002
2007.000000003
2007.000000004
2007.000000005
2007.000000006
I need to join this data to another table that does not have all the zeros after the decimal, can someone please show me how to get the data to look like below:
Year Docid
2007.1
2007.2
2007.3
2007.4
2007.5
2007.6
I am using MICROSOFT SQL SERVER 2012
If the format is fixed, i.e. YYYY.NNNNNNNNN, you could just get the last 9 characters, convert them to int, convert the result back to varchar and concatenate back to the first 5 characters:
LEFT([Year.Docid], 5) + CAST(CAST(RIGHT([Year.Docid], 9) AS int) AS varchar(10))
However, it would make more sense to store Year and Docid as two separate int columns, in both tables. It is much easier to assemble them just for the output than do this processing every time and join on the results of it.
In SQL Server, assuming both columns are varchar, something like this should do you:
select *
from table_1 t1
join table_2 t2 on t2.docid = left(t2.docid,4)
+ '.'
+ convert(varchar,convert(int,right( t2.docid, len(t2.docid)-5 )))
You should bear in mind that making the one table's column an expression means that for that table/column, the query optimizer cannot use any indexes in the query plan.
This is a bit of work, but accomplishes the task of removing the zeros from the right of the dot:
SELECT SUBSTRING(YearDocid, 0, CHARINDEX('.', yearDocId)) +
REPLACE(SUBSTRING(yearDocId,
CHARINDEX('.', yearDocId),
LEN(yearDocID)),
'0', '')
FROM tab1;
sqlfiddle demo
To turn the long format into the short format:
SELECT LEFT('2007.000000001',5) + CAST(CAST(RIGHT('2007.000000001',LEN('2007.000000001')-5) AS int)AS VARCHAR)
...
To use that in a join:
SELECT
...
FROM
TABLE_1 T1
INNER JOIN TABLE_2 T2
ON LEFT(T1.pk,5) + CAST(CAST(RIGHT(T1.pk,LEN(T1.pk)-5) AS int)AS VARCHAR) = T2.pk
SELECT CONCAT(PARSENAME([Col_Varchar],2),'.',CONVERT(INT,PARSENAME([Col_Varchar],1))) FROM Tbl_sample

SQL Doesnt Want to match strings with spaces for some reason

I have this SQL Query that is not comparing properly so I commented it out the WHERE clause. When returning the AF.ActivityNote it always has 2 spaces after it no matter if I do RTRIM on it or not. I think those spaces are the issue that wont let the commented WHERE clause to properly match the string against userfield33.
SELECT CAST(UF.UserField33 AS NVARCHAR) , RTRIM(CAST(AF.ActivityNote AS NVARCHAR))
FROM [BCMTEST01].[dbo].[ActivityContacts] as AC INNER JOIN [BCMTEST01].[dbo].[ActivityFullView] as AF
ON AC.ActivityID = AF.ActivityID INNER JOIN [BCMTEST01].[dbo].[OpportunityExportView] as OP
ON AC.ContactID = OP.ContactServiceID INNER JOIN [BCMTEST01].[dbo].[UserFields] as UF
ON OP.ContactServiceID = UF.ContactServiceID
WHERE ContactID = 8376
--WHERE RTRIM(CAST(UF.UserField33 AS NVARCHAR) = RTRIM(CAST(AF.ActivityNote AS NVARCHAR))
ORDER BY ContactID ASC
First, you should always include the length when converting to nvarchar, varchar, char, and nchar. So use something like:
cast(uf.userfield33 as nvarchar(255)) -- or whatever length you like, so long as you have something
The last two characters are not spaces. Do something like:
select ascii(right( AF.ActivityNote, 1))
To see what the character value is. You can then use replace to get rid of it. Or, you can just chop off the last two characters (if that works for your application).
By the way, I am assuming you are using SQL Server based on the syntax of the query.
Here is an alternative where clause:
where (case when right(AF.ActivityNote, 2) = char(10)+CHar(13)
then LEFT(AF.ActivityNote, LEN(AF.ActivityNote) - 2)
else AF.ActivityNote
end) = CAST(UF.UserField33 AS NVARCHAR(255)
I'm not a big fan of case statements in where clauses. I would actually put the logic in a subquery. Also, I might have the order of the 10/13 backwards.