SQL Server 2008
I have a query with several local variables that does some easy math in the result set. When I copy and paste the query to try to save it as a view, it fails telling me there’s incorrect syntax. (in this case it’s near the declare statement of the variables.) If needed I’ll post the query, just wondering if there’s a reason for this to work one way and not the other.
declare @totalpop float,
@totalMales float,
@totalFemales float,
@percentMales float,
@percentFemales float;
select @totalmales=sum(case when sex='m' then 1 else 0 end),
@totalfemales = sum(case when sex='f' then 1 else 0 end),
@totalpop=count(*)
from tblVisits
select @percentmales = round(100 * @totalmales/@totalpop,2),
@percentFemales = round(100*@totalfemales/@totalpop,2)
select @totalmales,@percentmales,@totalfemales, @percentfemales, @totalpop
You don’t need any of the declared variables, you can do this in plain-old sql with a nested select:
Which should be usable on most any database that supports views and subselects (which is basically all of them.