问题
ALTER PROCEDURE [dbo].[Create_Subjects]
@Subj_ID nvarchar(9)
AS
DECLARE @First3Digits nvarchar(3);
DECLARE @Result int;
DECLARE @Sql nvarchar(max)
-- Fetching the fiest 3 digits of the subject
SET @First3Digits = SUBSTRING(@Subj_ID,1,3);
-- Check if view is present or not
IF EXISTS (SELECT 1 FROM sys.views WHERE Name = @First3Digits)
BEGIN
SET @Sql = 'select @Result = case when exists (select 1 from dbo.' + quotename(@First3Digits) + ' where SubjectName = ''' + @Subj_ID + ''') then 1 else 0 end';
EXECUTE sp_executesql @Sql, N'@Subj_ID nvarchar(9), @Result bit out', @Subj_ID = @Subj_ID, @Result = @Result out;
-- checking if the subject is present in the view
END
ELSE
BEGIN
-- Create a view as view doesn't exist
SET @Sql = 'create view ' + @First3Digits
+ ' as
(select SubjectName from dbo.Subjects where SubjectName like '+@First3Digits+'%'+');';
EXECUTE sp_executesql @Sql, N'@First3Digits nvarchar(3)', @First3Digits= @First3Digits;
SET @Result = 0;
END
RETURN @Result
GO
This is the code for executing the stored procedure:
EXEC [dbo].[Create_Subjects] '1234567890'
Error encountered:
Msg 156, Level 15, State 1, Line 28
Incorrect syntax near the keyword 'view'Msg 102, Level 15, State 1, Line 29
Incorrect syntax near ')'
回答1:
There are a number of issues with your SQL. But firstly the way to debug them is to print the SQL without executing it, then its normal SQL and you can easily identify what is wrong with it.
- No brackets are allowed around the SQL making up the view.
- You have to quote your strings as per normal, which means doubling up the quotes in the dynamic string.
- Use
quotename
again as suggested in the comments. - There is no need to pass the parameter
@First3Digits
intosp_executesql
because by that point you've used its value - which you have to do given you are creating a view.
set @Sql = 'create view dbo.' + quotename(@First3Digits)
+ ' as'
+ ' select SubjectName'
+ ' from dbo.Subjects'
+ ' where SubjectName like ''' + @First3Digits + ''' + ''%'';';
-- This is how you debug dynamic SQL
print(@Sql);
execute sp_executesql @Sql;
Note: As I mentioned in your previous question, with the information provided, this seems to be a really bad design. There is almost certainly a better way to solve your bigger picture problem. As commented by Martin Smith an Inline Table Valued Function might be worth investigating.
来源:https://stackoverflow.com/questions/61668872/issues-encountered-with-dynamic-sql