Click here to Skip to main content
15,899,825 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
any help please appreciated,
as i am looking to work with dynamic variable table into sql stored procedure.
my code is below.

SQL
ALTER procedure [dbo].[emailListUpdate]
(
@EmailID as varchar(120),
@ListID as varchar(120)
)
as
declare 
@tablename as varchar(120)='EmailList'+@ListID
begin
set nocount on
if not exists (select top 1 * from [@tablename] where EmailID=@EmailID)
begin
insert into [@tablename](EmailID) values(@EmailID)
select result=2 --New List Inserted
end
else
select result=1--already exist with diffrent status update and return old status with id
set nocount off
end

exec dbo.emailListUpdate 219809,29
while running in such way i am gettting

Msg 208, Level 16, State 1, Procedure emailListUpdate, Line 12
Invalid object name 'dbo.@tablename'.
Posted

1 solution

SQL
DECLARE @SQL VARCHAR(MAX);

SET @SQL ='if not exists (select top 1 * from ['+@tablename+'] where EmailID='+@EmailID+')
begin
insert into ['+@tablename+'](EmailID) values('+@EmailID+')
select result=2
end
else
select result=1
'
EXEC (@SQL);


This is the solution found.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900