SQL CAST and SQL CONVERT function
In this article, we will learn SQL Cast and SQL Convert functions. Why do we use SQL Cast and SQL Convert functions?
Introduction
Sometimes we need to convert data from one data type to another data Type, then we use the cast and convert function in the SQL database.
So let's start with how can use the cast and covert function as an example.
CAST function in SQL.
Always remember that These functions cast and convert always use one data type to another data type value. The cast function we have used to
convert a datatype to another datatype without any specific format. as well as the convert function also converts value and formatting data type value at the same time.
Example:
SELECT (FirstName+SPACE(5)+LastName+SPACE(5)+CAST(Address AS VARCHAR(20)))
AS Fullname FROM Employee
SELECT CONVERT(VARCHAR(20), Pincode) AS Pincode FROM Employee
SELECT CAST(Pincode AS VARCHAR(20)) AS Pincode FROM Employee
------------------------------
07/08/2022
(1 row(s) affected)
------------------------------
Aug 7 2022 4:54PM
(1 row(s) affected)
Example: How to calculate date time to age.
DECLARE @dob DateTime
SET @dob='1995-12-20'
SELECT DATEDIFF(hour,@dob,GETDATE())/8766.0 AS AgeYearsDecimal
,DATEDIFF(hour,@dob,GETDATE())/8766 AS AgeYearsIntTrunc
,CONVERT(INT, ROUND(DATEDIFF(hour,@dob,GETDATE())/8766.0,0)) AS AgeYearsIntRound
Result:-
AgeYearsDecimal AgeYearsIntTrunc AgeYearsIntRound
--------------------------------- ---------------- ----------------
26.633013 26 27
(1 row(s) affected)
No comments:
Post a Comment