N'''2'',''3'''
is a scalar value - as in a string: "'2','3'". SqlServer treats it as a singular string, when you use it as a parameter in your query.
One solution could be to use WHERE IN (SELECT value FROM string_split(@Id, ','))
. which would split it into two strings: ["'2'","'3'"] - but again: strings with literal single-ticks in them. So when you CAST(Id as NVARCHAR(50))
you get your Ids as strings, but without the ticks: ["1","2","3"], which of course don't match.
So:
DECLARE @Id AS nvarchar(MAX) = N'2,3'
DECLARE @spparams as nvarchar(max) =N'@Ids nvarchar(MAX)'
EXEC sp_executesql N'SELECT * FROM temp_table where cast(Id AS nvarchar(50)) IN (SELECT value FROM string_split(@Ids,'',''))',@spparams,@Ids= @Id
An even better solution is to not treat numbers as strings
DECLARE @Id AS nvarchar(MAX) = N'2,3'
DECLARE @spparams as nvarchar(max) =N'@Ids nvarchar(MAX)'
EXEC sp_executesql N'SELECT * FROM temp_table where Id IN (SELECT convert(int, value) FROM string_split(@Ids,'',''))',@spparams,@Ids= @Id