Click here to Skip to main content
15,891,375 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have a sp which shd compare two tables together.
Everything looks fine but when i try to exec it, it comes out with
Incorrect syntax near the keyword FROM

Here my sp Statement:
SQL
SET @Dynamictb2 = N'SELECT DISTINCT [Projektdefinition DB] AS Zugänge
FROM [' + @Table_Name + ']'  +
'EXCEPT
SELECT DISTINCT [Projektdefinition DB] AS Zugänge
FROM' + @Table_Name

EXECUTE sp_executesql @Dynamictb2
Posted
Comments
CHill60 23-Oct-14 9:04am    
If you swap the "EXECUTE sp_executesql @Dunamictb2" for "PRINT @Dynamictb2" what is the resulting display ... that's the SQL that is failing
mikybrain1 23-Oct-14 9:20am    
thnx but it isn't working. Still the same message
CHill60 23-Oct-14 9:25am    
Did you try my solution and it's still not working??
mikybrain1 23-Oct-14 9:29am    
Yes just tried it. I even tought of two arguments like this but it isn't working too:
EXEC spDynamic1 '[dbo].[Per2011]', '[dbo].[Per2012]'

CHill60 23-Oct-14 9:36am    
If you just run SELECT DISTINCT [Projektdefinition DB] AS Zugänge
FROM [dbo].[Per2011]
EXCEPT
SELECT DISTINCT [Projektdefinition DB] AS Zugänge
FROM [dbo].[Per2012] which line does it report the error on?

1 solution

I ran your sql and swapped the EXECUTE for a PRINT and got this
SELECT DISTINCT [Projektdefinition DB] AS Zugänge FROM [xyz]EXCEPT SELECT DISTINCT [Projektdefinition DB] AS Zugänge FROMxyz

so I think this will fix your problem
SQL
SET @Dynamictb2 = N'SELECT DISTINCT [Projektdefinition DB] AS Zugänge
FROM [' + @Table_Name + ']'  +
' EXCEPT
SELECT DISTINCT [Projektdefinition DB] AS Zugänge
FROM ' + @Table_Name

Note the extra spaces before EXCEPT and after FROM on the 3rd and 5th lines respectively

EDIT - from OP comment we now know that this is within an SP called by
EXEC spDynamic1 '[dbo].[Per201102]'
so there are extra square brackets being inserted by the SET

Try this instead:
SQL
SET @Dynamictb2 = N'SELECT DISTINCT [Projektdefinition DB] AS Zugänge
FROM ' + @Table_Name + 
' EXCEPT SELECT DISTINCT [Projektdefinition DB] AS Zugänge
FROM ' + @Table_Name


EDIT2 - in response to OP comment - I think the SP needs to change similar to this (note - untested)
SQL
ALTER PROC spDynamic1
 (
 @Table_Name sysname ,@Table_Name2 sysname
 )
 AS
 BEGIN
 SET NOCOUNT ON;
 DECLARE @Dynamictb2 nvarchar(255)

 SET @Dynamictb2 = N'SELECT DISTINCT [Projektdefinition DB] AS Zugänge
 FROM [' + @Table_Name + ']' +
 ' EXCEPT
 SELECT DISTINCT [Projektdefinition DB] AS Zugänge
 FROM ' + @Table_Name2

 EXECUTE sp_executesql @Dynamictb2

 END
 GO 
 
Share this answer
 
v3

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