How to show decimal zeroes for a number in SQL Server - sql-server

I am pulling the following numbers from MS SQL Server:
345
345.6
345.67
How do I pull them so that they look like the following:
345.00
345.60
345.67
What datatype should they be stored as and what is the magic function to pull them?
Thank you.

You can use a cast function. Since you are pulling out values of a table, you would be using a select and some thing like the following can be used-
Select CAST(value AS DECIMAL(5,2)) from table
I hope that is what you are looking for.
cheers

Related

Convert number to varchar using to_varchar with leading zeros in Snowflake

In Snowflake there is a number column storing values like: 8,123,456. I am struggling determining how to structure select statement to return a value like: 00008123456.
In SQL SERVER you can do something like this:
right(replicate('0', 11) + convert(varchar(11), job_no), 11) AS job_no
I understand Snowflake to_varchar function can be used, but not sure how to structure like in SQL Server.
Just add a format string on to_varchar():
select to_varchar(8123456, '00000000000');
Give it try with: lpad(to_char(nos),11,0)
More examples & details: https://docs.snowflake.com/en/sql-reference/functions/lpad.html#examples
a solution provided by Greg Pavlik saved me.
I just switched from DB2 to Snowflake.
So, TO_VARCHAR( <numeric_expr> [, '<format>' ] ) worked.

Is there a way to extract individual values from a varchar column using SQL Server 2016?

I am trying to extract individual dates from a varchar column in a SQL Server 2016 tablet that are stored comma separated and am not sure how to proceed. The data is setup like this:
article Consolidation_Order_Cut_Off_Final_Allocation
------------------ ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
011040 01/13/2021,03/10/2021
019099 01/13/2021,01/27/2021,02/24/2021,03/24/2021,04/28/2021,05/26/2021,06/23/2021,07/28/2021
019310 01/27/2021,02/03/2021,03/10/2021,04/14/2021,05/12/2021,06/09/2021,07/14/2021,08/11/2021
059611 01/13/2021
Ideally - I would have each date split out into a new row. I have seen a few similar questions that use very complex functions but those seem to be for SQL Server 2008. I have also found the new function STRING_SPLIT but that would seem to be table valued and thus have to come in the FROM. One thought I had was to declare a variable to hold this column and then use something like select * FROM string_split(#dates,','); however since there is more than one value in that list that returns an error. I am very new to the 2016 version of SQL Server and curious if anyone has ran into a way to solve this.
String_Split() is a table valued function, so you can call it with a CROSS APPLY
Example or dbFiddle
Select A.article
,B.Value
From YourTable A
Cross Apply string_split(Consolidation_Order_Cut_Off_Final_Allocation,',') B

SQL Server - Set Date Format at insertion

Does anyone know the correct syntax for this format: dd-mmm-yyyy. E.g. 04-DEC-2016
Basic Insert
INSERT INTO GoodTbl (GoodID, GoodDate)VALUES (7,'12-04-2016')
I did this and it worked
INSERT INTO GoodTbl (GoodID, GoodDate)VALUES (7,(CONVERT(DATETIME,'12-04-2016', 105)));
but 106 is the correct code. However using 106 (as shown) does not work.
INSERT INTO GoodTbl (GoodID, GoodDate)VALUES (7,(CONVERT(DATETIME,'12-04-2016', 106)));
Is there a different way to write this?
If 2012+ you can use the format()
Select Format(GetDate(),'dd-MMM-yyyy')
Returns
03-Dec-2016
Another option is
Select Replace(convert(varchar(25),GetDate(),106),' ','-')
You realize that these conversions are string, so I am assuming the destination field is a string/varchar
Use VARCHAR instead of DateTime, then the following:
INSERT INTO GoodTbl (GoodID, GoodDate)
VALUES (7,Replace(convert(varchar(25),cast('2016-12-04' as date),106),' ','-'))

Using Sum(Cast(Replace syntax

I am trying to write a simple query in order to change some of our stage data. I have a varchar $ column (unfortunately) that needs to be summed. My issue is that because of commas, I cannot change the datatype.
So, I can use REPLACE(AMT,',','') to remove the commas but It still wont let me cast it as a decimal and I get
Error converting data type varchar to numeric.
I am trying the following below with no luck. Any ideas? Can this be done or am I using the wrong syntax here?
Select SUM(Cast(REPLACE(Amt,',','') as Decimal (18,2)) )
I was able to resolve this with #HABO suggestion. I used Cast(Ltrim(rtrim(table.AMT)) as Money) for all instances of the varchar amount. This removed white space and removed the commas from the numbers.
This should work... including an example.
Edit: if you are on SQL Server 2012+, you may be able to shorten your task by using Try_Convert
DECLARE #SomeTable AS TABLE (Amt Varchar(100));
INSERT INTO #Sometable (Amt) VALUES ('abc123,456.01'),(' 123,456.78 '),(Null),('asdad'),('');
With NumericsOnly AS
(
SELECT
REPLACE(Left(SubString(Amt, PatIndex('%[0-9.-,]%', Amt), 8000), PatIndex('%[^0-9.,-]%', SubString(Amt, PatIndex('%[0-9.,-]%', Amt), 8000) + 'X')-1),',','') AS CleanAmt
FROM
#SomeTable
)
SELECT
SUM(CONVERT(DECIMAL(18,2), CleanAmt)) AS TotalAmt
FROM
NumericsOnly
WHERE
IsNumeric(CleanAmt)=1
General methodology is taken from here
I wouldn't use money as a data type as it is notorious for rounding error.
The error is due to SQL order of operations within your SUM(CAST(REPLACE... operation. This issue can be resolved by summing the column AFTER it's been staged to be summed via a subquery:
SELECT SUM(Field),...
FROM ( SELECT
Cast(REPLACE(Amt,',','') as NUMERIC) as 'Field'
,...
) [Q]
If the table you're summing is administered by a BI Team, get them to stage the data there. Happy Data Happy life.

How to use extractvalue in SQL Server

I am trying to convert my Oracle query to SQL Server. The query shown below is causing some difficulty when trying to convert EXTRACTVALUE, XMLSEQUENCE, XMLTYPE functions.
Can anyone help me learn how to convert these to SQL Server?
EXTRACTVALUE(COLUMN_VALUE, 'pipeline/#name') NAME
FROM TABLE (SELECT XMLSEQUENCE(XMLTYPE(MESSAGE).EXTRACT('processEngine'))
FROM NMS_MESSAGES WHERE OBJECT_CODE='pe_monitor' AND ID=#WHERE:PARAM:USER_DEF:INTEGER:PARAM_PROCESS_ENGINE#)) INSTANCENAME
,(SELECT EXTRACTVALUE(COLUMN_VALUE, 'processEngine/#id') FROM TABLE (SELECT XMLSEQUENCE(XMLTYPE(MESSAGE).EXTRACT('processEngine'))
FROM NMS_MESSAGES WHERE OBJECT_CODE='pe_monitor' )) ENGINE_ID
Thanks in advance.
Think about XQuery. As I See that EXTRACTVALUE seems like #xml.values('(#node/#attr)[1]','type') and EXTRACT is #xml.nodes('path/path/path')
If know structure of xml that you ought to parse exactly than you will convert this query without any problems.

Resources