2

如果我通过 T-SQL 调用我的存储过程:

exec [dbo].[StoredProcedureName] '''Vijay'', ''Rana'', 1, 0'

在 SQL Server Mgmt Studio 中,它工作正常,但是当我从我的应用程序调用它时,它给了我错误

字符串 ''Vijay','Rana',1,0' 后面的非闭合引号。

我在谷歌上搜索并找到了这个EXEC sp_executesql @FinalQuery,但它不适合我

编辑
我这样称呼它

public virtual IDataReader ImportFirefighter(String  query)
{
        Database database = DatabaseFactory.CreateDatabase();
        DbCommand command = database.GetStoredProcCommand("[StoreProcedureName]");
        database.AddInParameter(command, "@query", DbType.String, query);

        IDataReader reader = null;

        try
        {
            reader = database.ExecuteReader(command);
        }
        catch (DbException ex)
        {
            throw new DataException(ex);
        }

        return reader;
    }

编辑我的完整商店程序

-- =============================================          
-- Author:  <Author,,Name>          
-- Create date: <Create Date,,>          
-- Description: <Description,,>          
-- =============================================         

--[dbo].[ImportIntoFirefighter]  '''Vijay'',''Rana'',''AC'',''AC'',''VOL'',1,0,0,1,1,''NA'','''',''VOL'','''','''',0,'''','''',0,1,1,'''',0&''Vijay21'',''Rana2'',''AC'',''AC'',''VOL'',1,0,0,1,1,''NA'','''',''VOL'','''','''',0,'''','''',0,1,1,'''',0&''Vijay32'',''Rana3'',''AC'',''AC'',''VOL'',1,0,0,1,1,''NA'','''',''VOL'','''','''',0,'''','''',0,1,1,'''',0&''Vijay42'',''Rana4'',''AC'',''AC'',''VOL'',1,0,0,1,1,''NA'','''',''VOL'','''','''',0,'''','''',0,1,1,'''',0'  


ALTER PROCEDURE [dbo].[ImportIntoFirefighter]         
@query VARCHAR(MAX)          

AS          
BEGIN         
DECLARE @TotalRecord int          
DECLARE @loopcount int          
DECLARE @TempQueryList TABLE                
  (             
  [ID] INT IDENTITY(1,1),                        
     [VALUE] VARCHAR(1000)                
   )           

DECLARE @Result TABLE                
  (             
  [iff_id] INT IDENTITY(1,1),                        
     [last_name] VARCHAR(50),        
     [first_name] VARCHAR(50),        
     [email] VARCHAR(50),        
     [mobile_number] VARCHAR(50),        
     [error] VARCHAR(max)              
   )           


   insert into @TempQueryList (VALUE) (           
   SELECT SUBSTRING('&' + @query + '&', Number + 1,          
    CHARINDEX('&', '&' + @query + '&', Number + 1) - Number -1)AS VALUE          
    FROM master..spt_values          
    WHERE Type = 'P'          
    AND Number <= LEN('&' + @query + '&') - 1          
    AND SUBSTRING('&' + @query + '&', Number, 1) = '&' )          

 Set @TotalRecord = (select count(*) FROM @TempQueryList)                   

  --select * from @TempQueryList          
   --Loop For Each Repeated Schedule           
 set  @loopcount = 1          
 WHILE @loopcount <= @TotalRecord            
  BEGIN          

  Declare @SingleQuery varchar(1000)        
  select @SingleQuery = Value  from @TempQueryList where id = @loopcount          

   BEGIN TRY        
   --print '[AddFirefighter] '  +  @SingleQuery        
   --SELECT 1/0;        

    --execute (@SingleQuery)    

    declare @FinalQuery varchar(max)   

   -- Select @SingleQuery =  LEFT(RIGHT(@SingleQuery, len(@SingleQuery)-1),len(@SingleQuery)-2)  


    set @FinalQuery = '[AddFirefighter] ' +  @SingleQuery  
        print  @FinalQuery  




  EXEC  (@FinalQuery)   


   END TRY        
   BEGIN CATCH        
   insert into @Result (last_name,first_name,email,mobile_number,error) values ( '','','','',ERROR_MESSAGE() )         
   -- Execute the error retrieval routine.            
   END CATCH         

  --print @loopcount          
  SET @loopcount = @loopcount + 1          

  END          

  select * from @Result        

--execute (@query)          
END 
4

3 回答 3

2

如果您使用的是 c# 和 asp.net,则应在代码中设置参数,而不是构建动态 sql 语句。如果您已经设置了存储过程,那么我没有理由调用动态 sql 语句并在字符串中构建参数。

这是使用存储过程对 sql 进行参数化调用的示例。 http://msdn.microsoft.com/en-us/library/yy6y35y8(v=vs.110).aspx

using (SqlConnection connection = new SqlConnection(connectionString))
{
// Create the command and set its properties.
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandText = "SalesByCategory";
command.CommandType = CommandType.StoredProcedure;

// Add the input parameter and set its properties.
SqlParameter parameter = new SqlParameter();
parameter.ParameterName = "@CategoryName";
parameter.SqlDbType = SqlDbType.NVarChar;
parameter.Direction = ParameterDirection.Input;
parameter.Value = categoryName;

// Add the parameter to the Parameters collection.
command.Parameters.Add(parameter);

// Open the connection and execute the reader.
connection.Open();
SqlDataReader reader = command.ExecuteReader();

if (reader.HasRows)
{
while (reader.Read())
{
Console.WriteLine("{0}: {1:C}", reader[0], reader[1]);
}
}
else
{
Console.WriteLine("No rows found.");
}
reader.Close();
}
于 2013-05-16T14:18:51.300 回答
2

如果您的存储过程根据您的问题需要四个参数,您可以将参数添加到 aSqlCommand然后执行命令。

    //Build your command
    SqlConnection conn = new SqlConnection(yourConnectionString);
    SqlCommand cmd = new SqlCommand("stored_procedure_name", conn);
    cmd.CommandType = CommandType.StoredProcedure;

    //Define the parameters to pass to the stored procedure
    cmd.Parameters.Add("@firstParameter", SqlDbType.NVarChar, 255);
    cmd.Parameters.Add("@secondParameter", SqlDbType.NVarChar, 255);
    cmd.Parameters.Add("@thridParameter", SqlDbType.Int);
    cmd.Parameters.Add("@fourthParameter", SqlDbType.Int);

    //Assign Values to the parameters
    cmd.Parameters["@firstParameter"].Value = "Vijay";
    cmd.Parameters["@secondParameter"].Value = "Rana";
    cmd.Parameters["@thirdParameter"].Value = 1;
    cmd.Parameters["@fourthParameter"].Value = 0;

    //Execute the command
    conn.Open();
    cmd.ExecuteNonQuery();
    conn.Close();
于 2013-05-16T14:21:51.433 回答
2

' 是分隔符所以在我看来你的字符串变成了 'Vijay','Rana',1,0 我认为你在同一个“字符串”中混合了字符串和数字你需要做的是传递 'Vijay',' Rana','1','0' (一串字符串),然后在你的过程中整理东西。为此,您传递的字符串应该类似于'''Vijay'',''Rana'',''1'',''0'''。根据您在存储过程中处理事物的方式,您甚至可能需要 '' '''' Vijay'''',''''Rana'''',''''1'''','''' 0'''' '' .Best 创建一个简单的过程,它只返回字符串作为测试台

于 2013-05-16T14:11:21.330 回答