I want to create a stored procedure..so before creating it I'm checking if the database and the table exist and then create the stored procedure. I'm using the below SQL script, but it throws syntax error. I have no clue why it is failing.
This is the error I get:
Msg 156, Level 15, State 1, Line 9
Incorrect syntax near the keyword 'PROCEDURE'.Msg 102, Level 15, State 1, Line 16
Incorrect syntax near ';'.Msg 102, Level 15, State 1, Line 2
Incorrect syntax near 'END'.
Code:
IF (EXISTS(SELECT TOP 1 * FROM sys.databases
WHERE name = 'testdb1'))
BEGIN
IF (EXISTS (SELECT TOP 1 *
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'dbo'
AND TABLE_NAME = 'TableA'))
BEGIN
CREATE PROCEDURE SP_TEST
AS
BEGIN
SET NOCOUNT ON;
SELECT TableA.[Key] AS Expr1
FROM testdb1.dbo.TableA
ORDER BY TableA.[Key];
END;
GO
END
END