I am trying to call a stored procedure from code using .Net Core 3.0 and SQL Server 2012, but I keep getting this error:
SqlException: Incorrect syntax near the keyword 'exec'. Incorrect syntax near ')'.
My code:
var policycontacts = await _dbContext.PolicyContacts
.FromSqlInterpolated($"exec dbo.spapi_contact_getbypolicy {input}")
.FirstOrDefaultAsync()
.ConfigureAwait(false);
SQL code:
EXEC Sp_executesql
N'SELECT TOP(1) [p].[ID], [p].[ActionsToTake],
[p].[AddedBy], [p].[BirthCountry], [p].[ContactGUID],
[p].[ContactID], [p].[ContactStatus], [p].[DOBFormation],
[p].[Domicile], [p].[EnhancedDueDiligence], [p].[EntityName],
[p].[EstimatedAmountAssets], [p].[FirstName], [p].[Gender],
[p].[HowClientMet], [p].[LastModifiedBy], [p].[LastModifiedDate],
[p].[LastName], [p].[LastOpenDate], [p].[LastOpenedBy],
[p].[MiddleName], [p].[Notes], [p].[OccupationBusiness],
[p].[OnlineUser], [p].[OpeningNotes], [p].[OriginAssets],
[p].[PEP], [p].[PEPDescription], [p].[PersonalSituation],
[p].[RiskOverride], [p].[Sysdate] FROM (exec dbo.spapi_contact_getbypolicy @p0)AS [p]',
N'@p0 nvarchar(4000)',
@p0=N''
Complete error:
Msg 156, Level 15, State 1, Line 3
Incorrect syntax near the keyword 'exec'Msg 102, Level 15, State 1, Line 4
Incorrect syntax near ')'
.AsAsyncEnumerable()afterFromSqlInterpolatedand switch to LINQ to Objects for the rest of the query. This would still execute the stored procedure for all results while discarding every row but the first; fixing that inefficiency would require rewriting to something that's not a stored procedure. - Jeroen MostertEXEC. Mapping the stored procedure in your data model to a method should allow for it, though -- the point is that the stored procedure result set is still just a result set that can be processed by clients in the same manner as regular queries, but you do need an ORM that cooperates for that. - Jeroen Mostert