I'm newbie in SQL and trying to create function in MS SQL 2008R2, but can't declare variable inside function. What's wrong with this code?
CREATE FUNCTION denominator() RETURNS int
BEGIN
DECLARE @Count;
-- Some logic here
END;
GO
SELECT dbo.denominator()
DROP FUNCTION denominator
I'm getting that kind of errors:
Msg 102, Level 15, State 1, Procedure denominator, Line 3
Incorrect syntax near ';'.
Msg 4121, Level 16, State 1, Line 1
Cannot find either column "dbo" or the user-defined function or aggregate "dbo.denominator", or the name is ambiguous.
The DECLARE statement is used to declare a variable in SQL Server. In the second step, we have to specify the name of the variable. Local variable names have to start with an at (@) sign because this rule is a syntax necessity. Finally, we defined the data type of the variable.
Declaring variables with the var keyword If the variable is declared outside of any functions, the variable is available in the global scope. If the variable is declared within a function, the variable is available from its point of declaration until the end of the function definition.
Syntax. If we want to declare a table variable, we have to start the DECLARE statement which is similar to local variables. The name of the local variable must start with at(@) sign. The TABLE keyword specifies that this variable is a table variable.
A CTE is an expression. In SQL, expressions are contained within statements, and never the other way around. Unless you are trying to make a view, you should be able to just put your DECLARE statements before the statement that contains your CTE's. As long as they are in the same batch, this should work.
you need to write like this , data type of variable is missing
DECLARE @Count int;
you're declaring of @Count
has no data type, you should provide it.
DECLARE @Count int
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With