I have a SQL query inside a stored procedure and I get an error.
Here is the query:
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[fPartnersDebt]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[fPartnersDebt]
/****** Object: UserDefinedFunction [dbo].[fPartnersDebt] Script Date: 03/07/2012 16:02:01 ******/
SET ANSI_NULLS ON
SET QUOTED_IDENTIFIER ON
exec('CREATE PROCEDURE [dbo].[fPartnersDebt]')
(
@StartDate datetime
,@EndDate datetime
,@CompanyName nvarchar(100)
,@Account nvarchar(100)
,@Reference nvarchar(max)
,@ShowClosedDocuments bit
)
RETURNS TABLE
AS
RETURN
(SELECT
t1.Name, t1.Bulstat, t1.Amount, t1.IsVat
FROM
(SELECT
c.CompanyID, c.Name AS [Name], c.IsVat, c.Bulstat AS [Bulstat],
SUM((ad.Amount + ad.RefAmount) * ad.[Sign]) AS [Amount]
FROM
Companies c
JOIN
AccountingDetails ad
JOIN
Accounts a
JOIN
AccountCategories ac ON ac.AccountCategoryID = a.AccountCategoryID
ON ad.AccountID = a.AccountID
JOIN
Accountings acc ON ad.AccountingID = acc.AccountingID
ON ad.CompanyID = c.CompanyID
LEFT JOIN
[References] r ON acc.OptionalReferenceID = r.ReferenceID
WHERE
ac.TypeIdentifier IN (4, 6, 7, 8, 9, 20, 33, 54, 10, 12, 13, 14, 15, 19, 34, 55)
AND Name LIKE @CompanyName
AND (a.Number = @Account OR a.Number LIKE @Account + '/%' OR (Len(@Account) < 3 AND a.Number LIKE @Account + '%'))
AND acc.AccountingDate >= @StartDate
AND acc.AccountingDate <= @EndDate
AND (ISNULL(r.[Description], '') LIKE @Reference + '%')
GROUP BY
c.CompanyID, c.Name, c.Bulstat, c.IsVat) t1
WHERE
@ShowClosedDocuments = 1 OR t1.Amount <> 0
)
Errors:
Incorrect syntax near '@StartDate'.
Must declare the scalar variable "@CompanyName".
I try to declare with many ways, but nothing does not work. Sorry but I'm new and it is a little hard to me to resolve this problem.