Forum Discussion

Joshua1627's avatar
Joshua1627
Copper Contributor
Feb 08, 2024

Must declare the scalar variable "@tableName".

i'm writing a stored procedure  , to get all the tablename present only in table1. and not in table2

tableName is the column name . but i'm getting the below error "Must declare the scalar variable "@tableName"."

 

CREATE PROCEDURE CheckRecordsInTable1
AS
BEGIN
SET NOCOUNT ON;

DECLARE @tableName NVARCHAR(255) = 'table1';

-- Check if records are present only in table1
IF NOT EXISTS (
SELECT tableName
FROM table1 t1
LEFT JOIN table2 t2 ON t1.id = t2.id
WHERE t2.id IS NULL
)
BEGIN
PRINT @tableName
END
ELSE
BEGIN
PRINT 'null';
END
END;

3 Replies

  • rmeldrum's avatar
    rmeldrum
    Copper Contributor
    You could try splitting up the declaration:

    DECLARE @tableName NVARCHAR(255)
    SET @tableName = 'table1';

    Also is it possible that when you ran the script you accidentally did not select the entire script? Sometimes when I am testing and only want to run part of a script I miss the variable declarations and get the same error.
  • olafhelper's avatar
    olafhelper
    Bronze Contributor
    Can't reproduce / confirm it, I don't get that error message with your code and reviewing the code, I can't see any failure.
    • Joshua1627's avatar
      Joshua1627
      Copper Contributor
      not sure why is not working for me . can you help in creating an SP , that will check if the record is present only in table1 and not table 2 and print the output
      if the output is null, it should print NULL , if the out put is list of records it should print those records

Resources