Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Views - no variables?

Tags:

tsql

sql-view

Is it possible to declare a variable within a View? For example:

Declare @SomeVar varchar(8) = 'something' 

gives me the syntax error:

Incorrect syntax near the keyword 'Declare'.

like image 887
PositiveGuy Avatar asked May 24 '11 18:05

PositiveGuy


People also ask

Can SQL views have variables?

No, we cannot use variables in a SQL Server View. This is because a view is just like a SQL statement with a name. Moreover, it does not exist physically in a database in SQL Server.

Can views have variables?

You can't declare variables in views. User stored procedure or function instead.

Can you use table variables in views?

Yes this is correct, you can't have variables in views (there are other restrictions too). Views can be used for cases where the result can be replaced with a select statement. A table function can be replaced with a select statement as well, but table functions cannot be used everywhere that a view can, such as joins.

Are SQL views read only?

Unlike base tables, VIEW s are either updatable or read-only, but not both. INSERT , UPDATE , and DELETE operations are allowed on updatable VIEW s and base tables, subject to any other constraints.


1 Answers

You are correct. Local variables are not allowed in a VIEW.

You can set a local variable in a table valued function, which returns a result set (like a view does.)

http://msdn.microsoft.com/en-us/library/ms191165.aspx

e.g.

CREATE FUNCTION dbo.udf_foo() RETURNS @ret TABLE (col INT) AS BEGIN   DECLARE @myvar INT;   SELECT @myvar = 1;   INSERT INTO @ret SELECT @myvar;   RETURN; END; GO SELECT * FROM dbo.udf_foo(); GO 
like image 199
spencer7593 Avatar answered Sep 21 '22 13:09

spencer7593