N
N
nrv2017-04-21 16:09:37
Transact SQL
nrv, 2017-04-21 16:09:37

How to push this code into a stored procedure?

Hello.
I have some code that works on its own, but I can't put it in a stored procedure. SQL Server 2008

USE STG3;
go
create proc [dbo].[nrv_test] as 
begin
drop table #t;
go

select 1 as val into #t;

if (SELECT COUNT(*) from #t) > 0
  raiserror('error number 1!!',16,1);

drop table #t;
go

select 2 as val into #t;

if (SELECT COUNT(*) from #t) > 0
  raiserror('error number 2!!',16,1);
end

Mistake

Incorrect syntax near ';'


There is already an object named '#t' in the database.


Incorrect syntax near 'end'.

UPD: while Google found out that go cannot be used in stored procedures, this does not cancel the problem, just the wording is slightly different:
USE STG3;
go

create proc [dbo].[nrv_test] as 
begin
drop table #t_nrv
select 1 as val into #t_nrv

if (SELECT COUNT(*) from #t_nrv) > 0
  raiserror('error number 1!!',16,1)

drop table #t_nrv

select 2 as val into #t_nrv

if (SELECT COUNT(*) from #t_nrv) > 0
  raiserror('error number 2!!',16,1)
end

Mistake
There is already an object named '#t_nrv' in the database

How to make SQL Server understand that before the select into goes, the table will already be dropped, despite the fact that the code must be in a stored procedure and go cannot be used there

Answer the question

In order to leave comments, you need to log in

3 answer(s)
N
nrv, 2017-04-21
@nrv

In one of the forums I found a reference to the documentation - I followed the link - indeed, it is impossible to create a table with the same identifier twice in the procedure. This is such a stupid limitation. So if the table is different every time, then just use a different identifier every time. I used one, so the code was of the same type and it was easy to copy-paste it.
Quote:
If more than one temporary table is created inside a single stored procedure or batch, they must have different names.
From here:
https://docs.microsoft.com/en-us/sql/t-sql/stateme...

A
Alexander, 2017-04-21
@NeiroNx

try without ';'

D
d-stream, 2017-04-21
@d-stream

Check for the presence of a table: there is a table - its id value will be, otherwise - null only if the table is needed exclusively inside the procedure - it is better to use not #table but @table otherwise there will be dances ...

declare @qqqq table (id primary key, value nvarchar(max))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question