ALTER PROCEDURE [dbo].[Create_Subjects]
@Subj_ID nvarchar(9)
AS
DECLARE @First3Digits nvarchar(3);
DECLARE @Result int;
-- Fetching the first 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
PRINT 'View exists'
-- checking if the subject is present in the view
IF EXISTS (SELECT 1 FROM @First3Digits WHERE SubjectName = @Subj_ID)
BEGIN
SET @Result = 1;
END
ELSE
BEGIN
SET @Result = 0;
END
END
ELSE
BEGIN
-- Create a view as view doesn't exist
EXEC('create view' + @First3Digits
+ 'as
(select SubjectName from dbo.Subjects where SubjectName like '+@First3Digits+'%'+');')
SET @Result = 0;
PRINT 'view does not exist'
END
PRINT @First3Digits
GO;
In the above code I am getting issues on the line
IF EXISTS (SELECT 1 FROM @First3Digits WHERE SubjectName = @Subj_ID)
Please help me to fix this issue.
@First3Digitsisn't a table variable, but might contain the name of a table, you'll need to make your problem statement dynamic SQL. Although three characters as used appears to preclude too much fun, see SQL Injection before going too far down the dynamic SQL rabbit hole.