Jason
Jason

Reputation: 87

Dynamic Sql Error , Invalid syntax near '>'

I have the below dynamic sql statement and I'm getting the "Incorrect syntax near '>'. error message. I can not figure out what the problem is, not sure if I'm missing a tick mark or not. I've tried to add extra tick marks and nothing seems to work.

Declare @filters varchar(max)
SET @filters = 'Where PaymentAmount > 0'
BEGIN 
SET @filters = @filters + ' AND CONVERT(DATE, AccountingDate) >= '''+ cast @BeginDate as nvarchar) + ''''
SET @filters = @filters + ' AND CONVERT(DATE, AccountingDate) <= '''+ cast(@EndDate as nvarchar) + ''''
END

SET @SQLString = 'Select 
  ,[ReturnDate]
  ,[PolicyNumber]
From dbo.Bil_ReturnsRepository' + @filters

EXEC(@SQLString)

Upvotes: 0

Views: 142

Answers (1)

squillman
squillman

Reputation: 13641

You need another space before you concat @filters to @SQLString.

SET @SQLString = 'Select 
  ,[ReturnDate]
  ,[PolicyNumber]
From dbo.Bil_ReturnsRepository ' + @filters

Otherwise the generated sql would be

...
From dbo.Bil_ReturnsRepositoryWhere PaymentAmount > 0
...

Upvotes: 3

Related Questions