2013-12-11 7 views
0

У меня есть хранимая процедура spSchedulerCheck, которая отлично работает с SQL Server. Он принимает один параметр, @jn. Попытка запускать это из VB/ASP.Net бросает мне синтаксическую ошибку (которую я ловил).Addwithvalue вызывает синтаксическую ошибку

VB код:

Public Function ScheduleCheck() 
    Dim sText As String 
    Using cn As New System.Data.SqlClient.SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings("ProductionDatabaseConnectionString1").ConnectionString) 
     cn.Open() 
     Dim cmd As New System.Data.SqlClient.SqlCommand("SchedulerCheck", cn) 
     cmd.Parameters.AddWithValue("@jn", Trim(Request.QueryString("jn").ToString())) 
     Try 
      Using reader As System.Data.SqlClient.SqlDataReader = cmd.ExecuteReader() 
       If reader.Read() Then 
        sText = reader(0).ToString() 
       End If 
      End Using 
     Catch ex As Exception 
      Return ex.Message 
     End Try 

     If Not cn Is Nothing Then 
      cn.Close() 
     End If 
    End Using 
     Return sText 
End Function 

SP:

USE [Production Database 2] 
GO 

/****** Object: StoredProcedure [dbo].[SchedulerCheck] Script Date: 12/11/2013 15:31:48 ******/ 
SET ANSI_NULLS ON 
GO 

SET QUOTED_IDENTIFIER ON 
GO 

-- ============================================= 
-- Author:  <Author,,Name> 
-- Create date: <Create Date,,> 
-- Description: <Description,,> 
-- ============================================= 
CREATE PROCEDURE [dbo].[SchedulerCheck] 
    -- Add the parameters for the stored procedure here 
    @jn as nvarchar(max) 

AS 
BEGIN 
    -- SET NOCOUNT ON added to prevent extra result sets from 
    -- interfering with SELECT statements. 
    SET NOCOUNT ON; 

    -- Insert statements for procedure here 
declare @pn nvarchar(10); 
set @pn = (select Proposalnumber from tblprj_management where jobnumber = @jn); 

select ReturnCode = case 
    when not exists (select * from tblprj_equipmentscope where jobnumber = @jn) 
     then 'Could not find scope' 
    when not exists (select * from tblprj_frcriteria where jobnumber = @jn and 'FR' in (select equipment from tblprj_equipmentscope where jobnumber = @jn)) 
     then 'Could not find FR Criteria entry' 
    when not exists (select * from tblprj_wccriteria where jobnumber = @jn and 'WC' in (select equipment from tblprj_equipmentscope where jobnumber = @jn)) 
     then 'Could not find WC Criteria entry' 
    when not exists (select * from tblprj_sctcriteria where jobnumber = @jn and 'SCT' in (select equipment from tblprj_equipmentscope where jobnumber = @jn)) 
     then 'Could not find SCT Criteria entry' 
    when not exists (select * from tblprj_accriteria where jobnumber = @jn and 'AC' in (select equipment from tblprj_equipmentscope where jobnumber = @jn)) 
     then 'Could not find AC Criteria entry' 
    when not exists (select * from tblprj_LFcriteria where jobnumber = @jn and 'LF' in (select equipment from tblprj_equipmentscope where jobnumber = @jn)) 
     then 'Could not find LF Criteria entry' 
    when not exists (select * from tblprj_laborest where proposalnumber = @pn) 
     and not exists (select * from tblprj_mfglaborest assy where proposalnumber = @pn) 
     then 'Could not find labor estimates' 
    else 'Success' 
    end 


END 

GO 

Мне кажется, что это должно возвращать один из сообщений в СП, не без ошибок. Фактически, запуск его с сервера SQL действительно выполняется, как ожидалось. Некоторое устранение неполадок также показывает, что он работает как ожидалось, когда я не предоставляю параметр, и только прихожу, когда я пытаюсь передать его. Что я делаю, это вызывает ошибку?

EDIT: Ошибка Syntax Error near SchedulerCheck

+0

Какая ошибка? – Szymon

+0

Добавлен в Редактировать внизу. – Crimius

ответ

2

При вызове хранимой процедуры необходимо изменить свойство CommandType от значения по умолчанию Text к StoredProcedure

Dim cmd As New System.Data.SqlClient.SqlCommand("SchedulerCheck", cn) 
    cmd.CommandType = CommandType.StoredProcedure 

В противном случае CommandText SchedulerCheck интерпретируется как обычный SQL текст (например, это был SELECT/INSERT/UPDATE/DELETE). Конечно, этот результат в синтаксической ошибке.

AddWithValue не имеет ничего общего с сообщением об ошибке

+0

Комментируя это, он запустил его нормально, без сообщения об ошибке. Отбросил меня. Благодаря! EDIT: только если для параметра задано значение по умолчанию, похоже. Виноват. – Crimius

2

Вы должны установить CommandType из прикажете быть StoredProcedure. Значение по умолчанию: Text.

cmd.CommandType = CommandType.StoredProcedure 
Смежные вопросы