How can I use a parameter that stands for a view name which I can pass into CREATE VIEW statement in SQL?
DECLARE @ViewName VARCHAR(40) = 'V_fooo'
CREATE VIEW @ViewName
AS
SELECT * from foods
Does not work due to a syntax error. How can I achieve this? Thanks.
You would have to do this using DYNAMIC SQL.
DECLARE @ViewName VARCHAR(40) = 'V_fooo'
DECLARE @SQL VARCHAR(MAX) =
'CREATE VIEW ' + @ViewName +'
AS
SELECT * from foods'
EXEC (@SQL)
DECLARE @Sql NVARCHAR(MAX);
DECLARE @View_Name NVARCHAR(128);
SET @View_Name = 'V_fooo'
SET @Sql = N'CREATE VIEW ' + QUOTENAME(@View_Name) +
N' AS SELECT * FROM dbo.foo_table'
EXECUTE sp_executesql @Sql
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.