stored proc to dynamically create view

arkiboys 9,621 Reputation points
2021-10-22T12:51:54.517+00:00

Hello,
Can you help me with building the stored procedure so that it creates view using dynamic sql?
I have difficulties with the single quote I think
Thank you

create procedure usp_Test
@SchemaName varchar(10),
@ObjectName varchar(20)
AS
declare @alenzi nvarchar(mx)
set @alenzi = '
CREATE OR ALTER VIEW ' + @SchemaName + '.' + @ObjectName AS
SELECT
*
FROM OPENROWSET(
BULK 'DBName/@ObjectName/year=/month=/day=*/**',
DATA_SOURCE = 'xyz',
FORMAT='PARQUET'
)
WITH(
DepartmentID INT,
Name NVARCHAR(100),
GroupName NVARCHAR(100),
ModifiedDate DATETIME2
)
AS [r]'

execute sp_executesql(@alenzi )

--------------------

exec usp_Test @SchemaName = 'b1', @objectName = 'Department'

--test if view is created
SELECT * FROM b1.Department

Transact-SQL
Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,552 questions
0 comments No comments
{count} votes

Accepted answer
  1. Tom Phillips 17,716 Reputation points
    2021-10-22T18:33:30.54+00:00

    You need to use 2 single quotes inside a string.

    set @sql = 'CREATE OR ALTER VIEW ' + @SchemaName + '.' + @ObjectName + ' AS
    SELECT
    FROM OPENROWSET(
    BULK ''DBName/@ObjectName/year=/month=/day=/**'',
    DATA_SOURCE = ''xyz'',
    FORMAT=''PARQUET''
    )
    WITH(
    DepartmentID INT,
    Name NVARCHAR(100),
    GroupName NVARCHAR(100),
    ModifiedDate DATETIME2
    )
    AS [r]'
    
    0 comments No comments

0 additional answers

Sort by: Most helpful