Skip to the content.

Like in most languages, SQL local variables must be uniquely named. If you’re seeing this, it means you have something like:

declare @id int;
-- some code...
declare @id int;

Simply change the name of one of the variables, or remove the redundant copy.

Note that the scope of SQL variables is “anywhere later in the code”; you cannot re-declare a local in a branch. For example, this is not valid:

if -- some test
begin
    declare @id int
    -- more code
end
else
begin
    declare @id int
    -- more code
end

You can, however, assign to @id in the else branch without declaring it there, since we are later in the code. Likewise, we can read @id below (and outside) the if scope. SQL has weird scope/declaration behavior!