I have a SQL Server Table with some basic Sales information as follows
SaleID | TotalValue | PaymentMethod | User | Date
--------|---------------|-------------------|-----------|--------------
1 | 10 | CASH | USER 1 | 2020-01-01
2 | 120 | DEBIT CARD | USER 2 | 2020-01-01
3 | 1000 | CREDIT CARD | USER 2 | 2020-01-01
4 | 305 | CREDIT CARD | USER 1 | 2020-01-01
5 | 15 | CASH | USER 5 | 2020-01-01
I need to write a Dynamic Procedure os something of the sort that's able to search for the sales information using an array of SaleIDs as a filter. It's a simple select query, as follows:
SELECT
[SaleID]
,[TotalValue] as 'Total Value'
,[Date] as 'Date'
FROM
[Sales]
WHERE
[SaleID] in (1, 2, 3, 4)
I created the following Stored Procedure so I can input an array of SalesID:
CREATE PROCEDURE [dbo].[usp_SearchSales]
(
@SaleID NVARCHAR(max)
)
AS
BEGIN
SET NOCOUNT ON;
DECLARE @SQL NVARCHAR(MAX)
DECLARE @ParameterDef NVARCHAR(500)
SET @ParameterDef = '@SaleID NVARCHAR(max)'
SET @SQL = 'SELECT
[SaleID]
,[TotalValue]
,[PaymentMethod]
,[User]
,[Date]
FROM
[Sales]
WHERE
-1=-1'
IF @SaleID IS NOT NULL
SET @SQL = @SQL+ ' AND SaleID in (@SaleID)'
EXEC sp_Executesql @SQL, @ParameterDef, @SaleID = @SaleID
END
GO
Then I execute the Procedure through the Exec command
EXEC [usp_SearchSales] @SaleID = '1, 2, 3, 4'
GO
Then the procedure returns the following error uppon execution:
Msg 245, Level 16, State 1, Procedure usp_SearchSales, Line 26 [Batch Start Line 49]
Conversion failed when converting the nvarchar value '1, 2, 3, 4' to data type int.
Here is a SQL Query to create and insert some values on the designed table
CREATE TABLE [Sales] (
[SaleID] int,
[TotalValue] float,
[PaymentMethod] varchar(50),
[User] varchar(50),
[Date] date
)
insert into sales values (1, 10, 'CASH', 'USER 1', '2020-01-01')
insert into sales values (2, 120, 'DEBIT CARD', 'USER 2', '2020-01-01')
insert into sales values (3, 10000, 'CREDIT CARD', 'USER 2', '2020-01-01')
insert into sales values (4, 305, 'CREDIT CARD', 'USER 1', '2020-01-01')
insert into sales values (5, 15, 'CASH', 'USER 5', '2020-01-01')
I need some help to create a procedure, or something of the sort, where an array of SalesIDs gives me back the Sales informations of those Sales.