将逗号分隔的参数传递给SQL中的存储过程

时间:2013-05-16 14:04:28

标签: c# asp.net .net sql

如果我从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 

3 个答案:

答案 0 :(得分:2)

嗯'是分隔符所以在我看来你的字符串变成'Vijay','Rana',1,0我认为你在同一个“字符串”中混合字符串和数字,你需要做的就是通过'Vijay ','Rana','1','0'(一串字符串)然后在你的程序中排序。要做到这一点,你传递的字符串应该是'''Vijay'',''Rana'',''1'','0'''。根据你处理存储过程中的内容,你甚至可能需要'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' 0''''''.Best创建一个简单的proc,它只是将字符串作为测试床返回

答案 1 :(得分: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();
}

答案 2 :(得分:2)

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

    //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();