Calling stored procedure from code causes error - sql-server

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 ')'

Not enough rep to leave a comment, so I have to leave you an answer. Sorry, I think this is more of a comment.
I have a "okay" recommendation, but it might not be the best answer. Depending on how complex your stored procedure is and if you really want to call it in the FROM section, then change your stored procedure into a table valued function. The reason why its a terrible recommendation is there are limitations and performance issues by using a function. I'd read up on the following articles and see which route you would like to take.
Table Valued Function Killing My Query Performance
https://blogs.msdn.microsoft.com/psssql/2010/10/28/query-performance-and-multi-statement-table-valued-functions/
Cross Apply with table valued function article:
https://www.sqlshack.com/the-difference-between-cross-apply-and-outer-apply-in-sql-server/
The other option could be the one where Sean Lange provided.

Related

Sometimes I get errors when calling GO in Scripts in SQL Server Management Studio

When I follow this alter function with a GO, I get a syntax error near the GO. Without the GO, it runs correctly.
I want to add those GO because I'm writing an script altering 50 functions (alter function needs to be the first instruction of a batch). The vast majority run correctly, but four of them raise the error on their GO line, like in this example.
ALTER FUNCTION dbo.f_cost_standar
(#article varchar(24),
#dataCost Datetime)
RETURNS decimal(18,5)
AS
BEGIN
DECLARE #resultat decimal(18,5)
SET #resultat = NULL
SELECT TOP 1 #resultat = preu
FROM costos_Standar
WHERE article = #article
AND #dataCost BETWEEN dataInici AND ISNULL(dataFinal, '31/12/2099')
ORDER BY dataInici DESC
RETURN #resultat
END;
GO
This is the error I get:
Msg 102, Level 15, State 1, Procedure f_cost_standar, Line 12 [Batch Start Line 0]
Sintaxis incorrecta cerca de 'GO'.
When does the go fail, and what can I do to fix it?
PS: Thanks to #JeroenMostert I've seen that the problem was a broken newline before the GO. Now it works nicely.

SQL Server 2000 Error Creating Function

I can't create a function in SQL Server 2000 in my database. So, I tried to use the example in the help (F1), but I have the same error.
CREATE FUNCTION CubicVolume
-- Input dimensions in centimeters
(#CubeLength decimal(4,1),
#CubeWidth decimal(4,1),
#CubeHeight decimal(4,1)
)
RETURNS decimal(12,3) -- Cubic Centimeters.
AS
BEGIN
RETURN ( #CubeLength * #CubeWidth * #CubeHeight )
END
Errors:
Msg 170, Level 15, State 1, Line 2 Line 2:
Incorrect syntax near 'FUNCTION'.
Msg 137, Level 15, State 1, Line 9
Must declare the variable '#CubeLength'.
I run this script for Database Northwind and it didn't have problem, so I don't understand what the problem is.
thank you for your answers.
The problem was resolved.
The problem was compatibility on the level as Aaron Bertrand said.
Click Right on Database -->Properties-->Options-->Compatibility Level
(Needs 80 or high)
enter image description here

Incorrect syntax near '('. Expecting ID - no idea how to fix this

Trying to create a new table from parts of an existing one using:
CREATE TABLE Spillover_HE
AS (SELECT * FROM [dbo].[Y16_GROW_Teacher]
WHERE HEDI = 'H');
And it keeps returning the error message:
Msg 102, Level 15, State 1, Line 2
Incorrect syntax near '('.
When I hover over the code it says:
Incorrect syntax near '('. Expecting ID.
I've tried changing the table name (same error), removing the WHERE statement (that generates an addition error of "Expecting UNION or EXCEPT"). I've read some answers to similar questions but am new to SQL and am very lost.
You should use SELECT INTO syntax:
SELECT * INTO Spillover_HE
FROM [dbo].[Y16_GROW_Teacher]
WHERE HEDI = 'H'
This will work on the MSSQL
SELECT * into Spillover_HE FROM [dbo].[Y16_GROW_Teacher]
WHERE HEDI = 'H'
Probably you are trying to create view.
CREATE VIEW Spillover_HE
AS ( SELECT *
FROM [dbo].[Y16_GROW_Teacher]
WHERE HEDI = 'H'
);

CASE STATEMENT for create view in SQL Server 2008

I have a create view query and I want to check if it does not exist yet, then create view. I tried to create like this:
CASE WHEN IS NOT EXISTS vw_Delays
THEN
VIEW vw_Delays AS
SELECT RD_RfileID_fk_ind, SUM(DATEDIFF(day, RD_Startdate, RD_EndDate)) AS delays FROM dbo.t_RfDelay
GROUP BY RD_RfileID_fk_ind
END
but it returns these errors:
Msg 156, Level 15, State 1, Line 1
Incorrect syntax near the keyword 'CASE'.
Msg 102, Level 15, State 1, Line 6
Incorrect syntax near 'END'.
How to solve this? Please can anyone help me to fix this ?
You need to use this code to check for the view's existence:
IF NOT EXISTS (SELECT * FROM sys.views WHERE Name = N'vw_Delays')
.....
The next obstacle you'll encounter is the fact that the CREATE VIEW statement must be the first of a SQL batch - so you cannot have it right after the existence check.
What I usually do is the opposite:
check if the view does exist
and if so - drop the existing view
then create the view from scratch
and I use this code for this setup:
IF EXISTS (SELECT * FROM sys.views WHERE Name = N'vw_Delays')
DROP VIEW dbo.vw_Delays;
GO
CREATE VIEW dbo.vw_Delays
AS
SELECT
RD_RfileID_fk_ind,
SUM(DATEDIFF(day, RD_Startdate, RD_EndDate)) AS delays
FROM
dbo.t_RfDelay
GROUP BY
RD_RfileID_fk_ind

SQL Server error

I am getting a fatal error on following code.
exec [sp_ExternalApp_UPDATEUSER] 'ZZZ', XXXXX','DDDDD','DDDFFDD','EREE', 'EREWWWWW',1,1,'QWEW#DFEE.DER','DEFF','XXXX','DDDD'
Following error occurred:
Location: memilb.cpp:1624
Expression: pilb->m_cRef == 0
SPID: 79
Process ID: 2256
Msg 3624, Level 20, State 1, Procedure sp_ExternalApp_UPDATEUSER, Line 32
A system assertion check has failed. Check the SQL Server error log for details
Msg 0, Level 20, State 0, Line 0
A severe error occurred on the current command. The results, if any, should be discarded.
Thank you
I got the solution.
I have used UPPER() function. As I removed that function, my problem solved
Like the message said, check your error log, there might be more detail in there..what does this proc do does it use sp_OACreate or calls xp_cmdshell? Post the proc code
You might want to check the database for corruption. Try
DBCC CHECKDB
(before doing so, read the documentation on that command! See http://msdn.microsoft.com/en-us/library/ms176064.aspx )

Resources