Cast and Convert functions in SQL Server Part 28

kudvenkat
2 Sept 201217:26

Summary

TLDRIn this SQL Server tutorial, the instructor Wenet explores the intricacies of data type conversion using CAST and CONVERT functions. The session clarifies when to use each function, highlighting that CAST adheres to ANSI standards, ensuring compatibility across databases, while CONVERT offers more flexibility, including the use of styles for formatting datetime. Practical examples demonstrate converting datetime to a string with specific formats and grouping data by date, emphasizing the importance of converting datetime to date when necessary. The tutorial also touches on concatenating data types and concludes with a comparison of CAST and CONVERT, recommending CAST for portability and CONVERT for its enhanced formatting capabilities.

Takeaways

  • 😀 The session focuses on learning about the CAST and CONVERT functions in SQL Server, which are used to convert data from one type to another.
  • 🔍 The CAST function is used to convert the data type of a column, such as changing the 'date of birth' from datetime to varchar for better display.
  • 📊 The CONVERT function is similar to CAST but offers additional flexibility, including the ability to specify a 'style' parameter to control the format of the converted data.
  • 📝 An example given is converting a datetime column to display the date in 'DD MM YYYY' format using the CONVERT function with style 103.
  • ❗ It's important to note that the LENGTH parameter in CAST and CONVERT is optional and can be used to specify the length of the converted data.
  • 📅 The CONVERT function is necessary when you want to control the formatting of date and time data types, which CAST does not support.
  • 💡 SQL Server 2008 introduced the 'date' data type, allowing for easier extraction of date parts without converting to varchar, which was necessary in SQL Server 2005.
  • 🔑 The script provides practical examples, such as concatenating an integer ID with a varchar name after converting the ID to varchar.
  • 🧩 Grouping data by date requires converting the datetime data type to just the date part to aggregate correctly, which can be achieved using either CAST or CONVERT.
  • 🌐 CAST is based on ANSI standards, making it more portable across different database applications, whereas CONVERT is specific to SQL Server and offers more functionality.

Q & A

  • What are the two functions in SQL Server used for data type conversion?

    -The two functions in SQL Server used for data type conversion are CAST and CONVERT.

  • What is the primary difference between the CAST and CONVERT functions?

    -The primary difference is that CONVERT has an optional style parameter, which CAST does not have. Additionally, CAST is based on ANSI standards, making it more portable across different database applications, while CONVERT is specific to SQL Server and offers more flexibility.

  • Why would you choose to use CAST over CONVERT in SQL Server?

    -You would choose to use CAST over CONVERT when portability is a concern, as CAST is based on ANSI standards and can be used across different database applications. It's also the choice when you do not need the style functionality provided by CONVERT.

  • How can you control the formatting of datetime data types in SQL Server?

    -You can control the formatting of datetime data types in SQL Server using the style parameter in the CONVERT function. This allows you to specify how the datetime should be displayed, for example, as 'DD MM YYYY' using style 103.

  • What is the purpose of the style parameter in the CONVERT function?

    -The style parameter in the CONVERT function is used to control the format of the output when converting datetime data types. It allows for various predefined formats to be applied to the converted data.

  • How can you obtain only the date part from a datetime data type in SQL Server?

    -To obtain only the date part from a datetime data type in SQL Server, you can use the CONVERT function with a style parameter that specifies only the date, such as style 1 ('YYYY-MM-DD') or style 101 ('YYYYMMDD'). Alternatively, you can convert the datetime to the 'date' data type using either CAST or CONVERT.

  • What is the syntax for using the CAST function in SQL Server?

    -The syntax for using the CAST function in SQL Server is: CAST (expression AS data_type [(length)]). The length is optional and depends on the target data type.

  • How do you concatenate a numeric column with a string column in SQL Server?

    -To concatenate a numeric column with a string column in SQL Server, you must first convert the numeric column to a string data type using either CAST or CONVERT, and then use the concatenation operator (+) to combine it with the string column.

  • What is the issue with grouping by a datetime column that includes both date and time in SQL Server?

    -Grouping by a datetime column that includes both date and time in SQL Server can result in no rows being grouped together because it's unlikely that multiple records will have the exact same date and time down to the second. To group by just the date, you should convert the datetime column to the 'date' data type using CAST or CONVERT.

  • How can you display a date in a custom format such as 'DD MM YYYY' in SQL Server?

    -You can display a date in a custom format such as 'DD MM YYYY' in SQL Server by using the CONVERT function with the appropriate style parameter, which in this case would be style 103.

Outlines

00:00

📘 Introduction to SQL Server's CAST and CONVERT Functions

This paragraph introduces the topic of the video, which is about the CAST and CONVERT functions in SQL Server. The speaker explains that these functions are used to convert data from one type to another and sets the stage for a detailed comparison between the two. An example is given involving a table with columns for ID, name, and date of birth, where the goal is to display the date of birth in a different format. The speaker demonstrates how both CAST and CONVERT can achieve the same outcome, converting the date of birth to a varchar format. The syntax for both functions is discussed, with an emphasis on the optional length parameter that can be used to specify the length of the converted data type.

05:00

🔢 Exploring the Style Parameter and Formatting Dates in SQL Server

In this paragraph, the focus shifts to the use of the style parameter in the CONVERT function, which is not available in the CAST function. The speaker illustrates how to format date and time data using different style numbers provided by Microsoft. An example is given where the date of birth is formatted to show only the date in a specific format (DD MM YYYY). The paragraph also touches on the importance of understanding the MSDN documentation, which lists various styles for different data types. The speaker emphasizes that while CAST and CONVERT can both convert data types, CONVERT offers more flexibility through the use of styles.

10:00

📅 Manipulating Date and Time Data in SQL Server Queries

The speaker continues the discussion on data type conversion by demonstrating how to extract just the date part from a datetime column. The paragraph explains that while the CONVERT function can be used with a style parameter to format the date, the CAST function cannot. It also introduces the 'date' data type introduced in SQL Server 2008, which allows for more straightforward extraction of the date part without converting to varchar. The paragraph includes a practical example of concatenating an integer ID with a varchar name, highlighting the need to convert the ID to varchar before concatenation.

15:02

📊 Grouping Data by Date and Understanding CAST vs CONVERT

This paragraph presents a practical scenario where the speaker wants to count the total registrations by date, ignoring the time part. The speaker shows how to use the CAST function to convert the datetime data to just the date data type for proper grouping. The paragraph concludes with a comparison between CAST and CONVERT, highlighting that CAST is based on ANSI standards and thus more portable across different database applications, while CONVERT is specific to SQL Server and offers more flexibility, including the use of styles for formatting.

Mindmap

Keywords

💡SQL Server

SQL Server is a relational database management system developed by Microsoft. It is used to store, manage, and retrieve data in a structured format. In the video, SQL Server is the platform on which the discussed functions and techniques are applied, specifically for data type conversion using CAST and CONVERT functions.

💡CAST function

The CAST function in SQL Server is used to convert a value from one data type to another. It is part of the ANSI SQL standard, making it a portable choice for database operations. In the video, the CAST function is demonstrated to convert the 'date of birth' column from a DATETIME data type to a VARCHAR data type, allowing for customized formatting.

💡CONVERT function

The CONVERT function is another tool in SQL Server for data type conversion, with the added flexibility of a 'style' parameter to control the format of the converted data. Unlike CAST, CONVERT is specific to SQL Server and offers more control over the output format, as shown in the video when converting dates to a specific string format.

💡Data type conversion

Data type conversion refers to the process of changing data from one format to another, which is a common task in database management. In the video, the concept is central as it discusses the use of CAST and CONVERT functions to convert data types, such as transforming DATETIME to VARCHAR for better presentation.

💡VARCHAR data type

VARCHAR is a variable-length character data type in SQL Server used to store strings. The video uses VARCHAR as a target data type when converting columns like 'date of birth' to display them in a more readable format, such as including month names and AM/PM indicators.

💡DATETIME data type

DATETIME is a data type in SQL Server that stores both date and time. The video script includes an example where DATETIME data is converted to a more user-friendly format using the CAST and CONVERT functions, highlighting the importance of data type conversion for reporting and user interface display.

💡Style parameter

The style parameter is an optional feature of the CONVERT function that allows for specific formatting of date and time data. The video explains how to use style parameters to control the output format of date conversions, such as displaying dates in 'DD MM YYYY' format, which is crucial for generating reports with a consistent look.

💡Group By

Group By is a clause in SQL used to group rows that have the same values in specified columns into summary rows, like 'find the number of customers in each country'. In the video, Group By is used to count total registrations by date, but requires the conversion of DATETIME to DATE to group by day only.

💡Concatenation

Concatenation in SQL is the process of joining two or more strings together. The video demonstrates concatenation when combining an ID (converted to VARCHAR) with a name to create a new column 'name-ID', illustrating the necessity of data type conversion for string operations.

💡MSDN documentation

MSDN (Microsoft Developer Network) documentation is a resource for developers to find technical information and guidelines for Microsoft technologies. The video references MSDN for details on style parameters and data type conversion, emphasizing the importance of consulting official documentation for accurate and detailed guidance.

Highlights

Introduction to SQL Server's cast and convert functions for data type conversion.

Demonstration of converting date of birth to a formatted string using cast and convert functions.

Explanation of the syntax and usage of the cast function with an example.

Discussion on the optional length parameter in cast and convert functions.

Example of specifying the length parameter to control the output format.

Introduction to the convert function and its syntax.

Explanation of the optional style parameter in the convert function.

Practical example of using the style parameter to format date and time.

Guidance on how to read MSDN documentation for optional parameters.

Illustration of converting datetime to just the date part using the convert function.

Introduction of SQL Server 2008's date data type and its use in conversion.

Example of concatenating integer and string data types using cast function.

Real-world example of aggregating registrations by date using group by clause.

Explanation of why grouping by datetime fails and the solution using the date data type.

Discussion on the differences between cast and convert functions.

Recommendation on when to use cast or convert based on portability and functionality needs.

Conclusion and resources for further learning on SQL Server and related topics.

Transcripts

play00:00

hello welcome to preim Technologies I am

play00:02

wenet this is part 28 of SQL server in

play00:05

this session we'll learn about the cast

play00:07

and convert functions when to choose one

play00:09

over the

play00:11

other now in SQL Server to convert one

play00:14

data type to another we have two ways

play00:17

cast and convert functions can be used

play00:20

now before looking at the syntax of the

play00:22

cast and convert functions let's look at

play00:24

an example now if you look at this table

play00:26

I have got three columns ID name and

play00:28

date of birth now what I want to do is

play00:31

in the output you know I want the output

play00:33

like this the second table we have here

play00:35

ID name date of birth as it is and a

play00:38

converted date of birth now in the

play00:40

output I want a three-letter month name

play00:43

and an AM PM for the time instead of

play00:46

displaying it like this I want you know

play00:49

the date to be displayed as shown in the

play00:51

converted date of birth column okay so

play00:54

obviously in order to achieve that we

play00:56

have to convert date time date of birth

play01:00

column into nare care column and to do

play01:04

that we can use so we are basically

play01:06

converting one data type to another so

play01:08

to do that we have cast and convert

play01:10

functions now if you look at these two

play01:13

queries here the first and second

play01:14

queries these two queries give the same

play01:17

output that you see on this second table

play01:19

here okay so what are we doing in the

play01:21

output we want ID name date of birth and

play01:24

converted DB uh date of birth so four

play01:26

columns so ID name and date of birth as

play01:29

usual and I I want the converted date of

play01:31

birth column so in order to convert the

play01:34

date of birth I'm using the cast

play01:36

function okay so cast and I'm saying C

play01:40

con cast this date of birth to envir

play01:44

care okay so if you look at the syntax

play01:47

uh cast expression or column name as

play01:52

your target data type our Target data

play01:54

type here is nare care and if you look

play01:57

at there we have another piece to it we

play01:59

have have this length within square

play02:02

brackets which means whatever is

play02:04

specified in square brackets is optional

play02:07

that's how we read mstn documentation if

play02:10

they have specified anything within the

play02:12

brackets then that means that part is

play02:14

optional so we have't specified the

play02:17

length here if you want to you can

play02:18

specify the length let's look at that

play02:20

quick example of how to specify the

play02:22

length so if you look at this particular

play02:24

example select star from TBL employees I

play02:27

get ID name datea of birth now what we

play02:29

want is we want to convert the date of

play02:31

birth into n car column and to do that

play02:33

we are using the cast function passing

play02:35

in date of birth column and asking it to

play02:38

convert to nare care okay and we are

play02:40

giving it an alas name as convert as

play02:43

converted date of birth so when I

play02:45

execute that we should get the converted

play02:47

date of birth okay now here for the

play02:50

Target data type we are not specifying

play02:52

the length if you wish you can specify

play02:55

the length for example let us say if I

play02:57

say the length is five convert the date

play03:00

time date of birth to enare care of

play03:02

length five so obviously when we execute

play03:04

this query as you might expect you know

play03:07

the output will be knocked off to Five

play03:10

Characters okay so you may want to be

play03:12

careful when you specify that length on

play03:14

the other hand when I specify 10 you

play03:16

know still something is knocked off so

play03:19

maybe when I specify 11 we get

play03:21

everything back but we don't get the

play03:24

time so if you want time maybe you will

play03:26

have to slightly increase that to maybe

play03:29

20 yep we get the time as well okay now

play03:33

so that's the Syntax for cast function

play03:36

cast your Source column as Target data

play03:39

type and length of the target data type

play03:42

is optional okay and the same is the

play03:45

case as convert function if you look at

play03:46

the convert function you specify the

play03:48

target data type first we want to

play03:50

convert to nare comma and your Source

play03:54

column which is nothing but our date of

play03:56

birth column and if you look at the

play03:58

syntax from MSD in here it says this is

play04:01

the target data type and obviously

play04:03

length is optional again because that's

play04:05

present in the square brackets and your

play04:07

Source column or expression and if you

play04:09

look at this here we have another third

play04:11

parameter for convert function in this

play04:14

query we haven't used that but there is

play04:16

another third optional parameter which

play04:18

is the style parameter we'll talk about

play04:20

that in a bit okay but understand that

play04:23

there is this third parameter called

play04:25

style for convert but cast doesn't have

play04:27

that okay so obviously both of these

play04:30

queries give us the same output as you

play04:32

see here on this table Okay cool so

play04:36

let's execute those two queries and make

play04:38

sure we get the same

play04:40

output okay so we get the same output

play04:43

now let's look at this example let's see

play04:45

how to use the style parameter um okay

play04:49

so what I want to do is in this in the

play04:52

first example that we have seen we are

play04:54

converting the date of birth to nare

play04:58

care but we don't really have have the

play05:00

control on how we want this you know

play05:02

date time to be

play05:04

formatted okay but if you want to

play05:06

control how that date time should be

play05:09

formatted then msdn I mean Microsoft has

play05:12

provideed us with a lot of

play05:14

styles okay so for example I want you to

play05:17

write a query now which gives me the

play05:20

date of birth like this I just first

play05:22

thing is I just want only the date and

play05:25

that too the date should be in DD mm y y

play05:30

y format okay so to do that we are using

play05:34

the convert function you cannot do that

play05:35

using cast function you'll have to use

play05:38

convert function so I'm using the

play05:40

convert function and I'm saying okay

play05:41

convert the date of birth to nare care

play05:44

and then I'm using the third optional

play05:46

style parameter as well so for style

play05:49

parameter this is the third parameter so

play05:51

for the third parameter I'm using 103 so

play05:55

what does 103 mean check this table 103

play05:58

means TD mm y y y okay now do I need to

play06:03

remember all these integer numbers now

play06:05

not only these there are several of them

play06:08

okay I just picked a few from the msdn

play06:10

documentation there are literally you

play06:12

know 20 to 30 Styles there on the msdn

play06:14

website okay so we don't have to really

play06:16

remember them if you just search Google

play06:19

you know datetime Styles in SQL Server

play06:21

you'll get that as the first article

play06:24

okay so we are basically saying convert

play06:26

this to ddmm y y y and we have the

play06:28

output

play06:30

okay so if you want to control how the

play06:32

output date and time to be formatted you

play06:34

can use Styles okay now not only date

play06:38

and time even if you want to format

play06:39

decimals the way you want it you can use

play06:41

Styles okay so all the styles for all

play06:44

the related data types are present on

play06:47

msdn at this URL if you wish to check

play06:49

them so so far what we have seen uh we

play06:52

have understood that there are two ways

play06:54

to convert from one data type to another

play06:56

cast and convert what is the difference

play06:58

between them convert has an optional

play07:01

style parameter whereas cast doesn't

play07:03

have it okay we'll look at more

play07:05

differences between cast and convert in

play07:07

a bit okay also we have seen how to read

play07:10

the msdn documentation so according to

play07:12

the msdn documentation if something is

play07:14

in within the square brackets then that

play07:17

piece is optional you may or may not

play07:18

provide that just like length and style

play07:24

parameters all right now let's look at

play07:27

how to get just the date part in the

play07:29

previous example we have seen how to get

play07:31

just the date part you know we are

play07:33

converting the date of birth to n care

play07:36

and we are using 103 style not only 103

play07:39

you can also use 101 or one2 depending

play07:42

on which style you want all of them will

play07:44

give you just the date so that's one way

play07:46

convert it to nare care and specify the

play07:49

style you want okay so that's one way

play07:52

and that's exactly here that's one way

play07:54

to get just the date part of a complete

play07:57

date time okay

play08:00

but in SQL Server 2008 we have this date

play08:03

data type introduced in SQL Server 2005

play08:07

we only have date time okay but in SQL

play08:10

Server 2008 they have um date time date

play08:14

as well as time three different

play08:16

parameters um data type sorry um so

play08:19

since we have a whole you know just the

play08:22

date data type what you can do is

play08:24

instead of converting a datetime data

play08:27

type to an where care you can say okay I

play08:31

will convert it to just date which will

play08:34

give you the date part just the date

play08:36

part okay and you can do that either

play08:39

using cast or convert function okay but

play08:43

to control the formatting of the date

play08:45

part you still have to use you know you

play08:48

still have to convert the date time to

play08:51

nare care using the Styles provided when

play08:54

converting to date data type the convert

play08:57

function will ignore the St style

play09:00

parameter okay the convert function will

play09:02

respect the style parameter only if

play09:04

you're converting it to Vare or nare you

play09:07

know basically the to the string data

play09:10

type all right so that's about how we

play09:12

want to convert you know date time just

play09:15

to date okay another simple example that

play09:18

I want to show you is um look at this I

play09:21

have the ID of the person and the name

play09:22

of the person um I want the name- ID

play09:28

okay so name name- ID both in the same

play09:31

column so how do I do that obviously

play09:34

since ID is integer and if you want to

play09:36

concatenate that integer with the name

play09:39

of the person obviously you will have to

play09:41

convert that ID to nare care and that's

play09:44

exactly what we are doing here select ID

play09:47

name both the columns as usual and then

play09:50

I'm saying select name to the name

play09:53

concatenate hyphen I mean the dash and

play09:56

to that concatenate ID

play10:00

after converting it to andare Let's

play10:02

quickly do that okay so what we want we

play10:06

want select

play10:10

ID comma

play10:12

name um and I want

play10:17

ID sorry name to the name we want to

play10:23

concatenate

play10:25

Dash and to that we want to concatenate

play10:28

the ID ID from TBL employees table let's

play10:33

execute this and see what happens

play10:35

obviously we get an error conversion

play10:37

failed when converting the nare care

play10:39

value to data type integer and that

play10:42

makes sense you're trying to concatenate

play10:44

this integer to this

play10:49

name you know which is nare care it's

play10:51

not possible and you are you doing that

play10:53

using the plus sign okay so that's why

play10:57

you have to convert this to bar car you

play10:59

can either use cast or convert I'm using

play11:02

cast here cast ID as Nar

play11:08

care and then when we execute this

play11:10

obviously we'll get the output as

play11:12

expected and if we want to give a column

play11:15

name to that we use the alas as maybe

play11:19

name-

play11:21

ID so when we execute that we should get

play11:23

the output that we are

play11:25

expecting

play11:28

okay so we'll look at another you know

play11:31

real practical example and to understand

play11:34

this better I have this table called TBL

play11:37

registrations so let's look at that

play11:39

select star from TBL registrations table

play11:43

so if you check this table okay let's go

play11:46

back to the slides if you check this

play11:47

table there are users who are registered

play11:51

and there is this registered date so if

play11:53

you look at this one two you know there

play11:56

are two people who have registered on

play11:58

25th and there are 1 2 three people who

play12:01

are registered on 24th and there's one

play12:03

person who is registered on 26th now

play12:05

what I want you to do is I want you to

play12:07

write a query which will give me the

play12:09

total registrations by the date I don't

play12:12

really care at what time they have

play12:14

registered but I want the total count of

play12:18

registrations by the date okay so if you

play12:21

look at this I can clearly say 24th you

play12:24

know most registrations happened on 24th

play12:27

3 that's the highest and least number of

play12:30

registrations on 26th okay so obviously

play12:32

if we have to do this we use Group by

play12:35

class again if you're new to group by um

play12:37

please check the earlier um you know

play12:40

Parts in this video series so now let us

play12:43

see how to write this query and

play12:44

obviously if you look at this here it's

play12:46

pretty simple in the output what you

play12:48

want you want the registration date and

play12:50

total registrations so we will select

play12:52

the registration date okay let's first

play12:56

write this

play12:57

query okay so in the output we want the

play13:02

registration date so what we need to do

play13:05

is we need to select the registration

play13:07

date so

play13:09

registration date and what else we want

play13:13

we want count

play13:15

of

play13:17

ID as let's say

play13:20

total from which table we want that from

play13:24

the registrations table so TBL

play13:27

registrations and we want want to group

play13:31

by registration date because we want to

play13:34

count the total number of registrations

play13:41

by date so we are grouping by

play13:44

registration date so when I execute this

play13:46

look at what's going to happen uh

play13:48

invalid column name registration date

play13:50

let's

play13:55

see so what has gone wrong there

play13:57

registered date not registration

play14:00

registered

play14:16

date

play14:22

huh okay so let's execute that now if

play14:25

you look at the output this is um this

play14:27

is not what we expected

play14:29

now why did we get this output because

play14:32

you are saying Group by registered date

play14:34

but within the date we have got date and

play14:37

time as well at the same date and time

play14:40

nobody has registered that's why it's

play14:42

not grouping anybody it's in fact

play14:44

grouping but there is but there is no

play14:46

one who is registered on the same date

play14:49

and same time okay so if you want to

play14:53

group just by the date then you'll have

play14:55

to convert this to date data type so

play14:59

let's convert this to date data type and

play15:01

to do that we can use cast register date

play15:06

as we can use

play15:09

the date data

play15:13

type so we need to do the same thing

play15:16

even in the select list because we don't

play15:17

want the time we just want the date and

play15:19

we want to group by that date okay so

play15:22

when we execute that you should get the

play15:25

output as expected and obviously we will

play15:27

not have the column name if you want the

play15:29

column name just give the

play15:34

alas registration date so obviously when

play15:37

we execute this we should get the output

play15:40

as

play15:42

expected okay so this query when you

play15:45

have casted the date to I mean the date

play15:48

time data type to date you are able to

play15:50

group them correctly as you expect by

play15:53

day otherwise we got the output as shown

play15:56

here which is incorrect which is not

play15:58

what we want

play16:00

and finally we'll talk about the

play16:01

differences between cast and convert

play16:04

okay so you know if we want to convert

play16:06

from one data type to another data type

play16:08

we have two ways why do we have two ways

play16:09

in the first place why do we have these

play16:11

two different functions

play16:14

Now cast is actually an NC standard okay

play16:17

it's based on standards so obviously if

play16:20

it's based on standards then that

play16:22

function can be used on different

play16:25

database

play16:26

applications okay so if portability is a

play16:29

concern and if you want to use the

play16:31

script that you have written with other

play16:32

database applications use cast because

play16:35

it's based on ANC standard whereas

play16:37

convert is specific to SQL Server okay

play16:40

but the advantage of using convert is

play16:42

that it provides more flexibility than

play16:45

cast and we have seen examples where uh

play16:48

we have actually controlled how we want

play16:50

datetime data types to be converted

play16:52

using styles with the convert function

play16:55

okay with the cast function we cannot

play16:57

use style parameter meter okay now when

play17:01

do you when should you use one over the

play17:03

other now the general rule is since cast

play17:06

is based on ANC standard use cast okay

play17:10

unless you want to take the advantage of

play17:13

the style functionality in convert

play17:16

function okay on this slide you can find

play17:19

resources for asp.net and C interview

play17:21

questions that's it for today thank you

play17:23

for listening have a great day

Rate This

5.0 / 5 (0 votes)

Ähnliche Tags
SQL ServerData ConversionCast FunctionConvert FunctionDate FormattingString ManipulationData TypesProgramming TutorialDatabase ManagementMicrosoft Technologies
Benötigen Sie eine Zusammenfassung auf Englisch?