Home Adding a function to a variable in SQL Server 2008
Reply: 0

Adding a function to a variable in SQL Server 2008

user1028
1#
user1028 Published in June 23, 2018, 5:31 pm

I'm having trouble wrapping my head around using a variable to store a function. I want to store the following function in a variable:

declare @agegroup int
set @agegroup = datediff(year, convert(date, p.date_of_birth), getdate())

Doing this produces an error:

Msg 241, Level 16, State 1, Line 3
Conversion failed when converting date and/or time from character string.

I believe that this is happening because SQL doesn't know what p.date_of_birth is yet. It's a column from a table in a query.

select p.date_of_birth from person p

I will need to reference the function in the variable numerous times in the query (once it's complete), so I want to neaten up my query by using a variable. It this possible?

Edit: I was asked to include some data for the field in my sample code. The DOB is stored as a string: yyyymmdd

19350919
19370607
19370607
19400814
19410128
19410128
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.319252 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO