I'm just trying to run the code I got from one of the sites on the internet ( https://www.mssqltips.com/sqlservertip/1599/cursor-in-sql-server/ ) which aims to give 'VIEW' access to every object in the database
This is my code:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[dba_ExecGrantViewDefinition]
(@login VARCHAR(30))
AS
SET NOCOUNT ON
CREATE TABLE #runSQL
(runSQL VARCHAR(2000) NOT NULL)
--Declare @execSQL varchar(2000), @login varchar(30), @space char (1), @TO char (2)
DECLARE @execSQL VARCHAR(2000), @space CHAR (1), @TO CHAR (2)
SET @to = 'TO'
SET @execSQL = 'Grant View Definition ON '
SET @login = REPLACE(REPLACE (@login, '[', ''), ']', '')
SET @login = '[' + @login + ']'
SET @space = ' '
INSERT INTO #runSQL
SELECT @execSQL + schema_name(schema_id) + '.' + [name] + @space + @TO + @space + @login
FROM sys.all_objects s
WHERE type IN ('P','V','FN','IF','TF')
AND is_ms_shipped = 0
ORDER BY s.type, s.name
SET @execSQL = ''
Execute_SQL:
SET ROWCOUNT 1
SELECT @execSQL = runSQL FROM #runSQL
PRINT @execSQL --Comment out if you don't want to see the output
EXEC (@execSQL)
DELETE FROM #runSQL WHERE runSQL = @execSQL
When i executed this code to one of my object with name 'dbo.testing_2022-03-17'
I get the following error
Msg 102, Level 15, State 1, Line 8
Incorrect syntax near '-'.
can someone suggest what is not in accordance with the code in my object name
Apart from some of the issues mentioned in the comments, the reason behind the error seems to be the original author used [name]
to add the table name, rather than actually adding the square brackets around the name
column.
Change this line:
SELECT @execSQL + schema_name(schema_id) + '.' + [name] + @space + @TO + @space + @login
To:
SELECT @execSQL + QUOTENAME(schema_name(schema_id)) + '.' + QUOTENAME(name) + @space + @TO + @space + @login
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.