【问题标题】:Passing comma delimited parameter to stored procedure in SQL将逗号分隔的参数传递给 SQL 中的存储过程
【发布时间】:2013-05-16 14:04:27
【问题描述】:

如果我通过 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 

【问题讨论】:

  • 如何在C#中执行SQL语句?你能显示那个代码吗?
  • 您的 qeury 中 ' 的数量不均匀。在 Vijay 之前,您有 3 个起始 `,Rana 周围的正确数字,只有一个结束 ` 大约 1.0。
  • 请记住,在 C# 中您应该使用" 双引号来传递整个字符串,' 单引号只能用于字符周围。
  • @Tallmaris: 我正在使用字符串 "'" + Vijay + "'" 和字符串生成器来构建我的字符串

标签: c# asp.net .net sql


【解决方案1】:

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

【讨论】:

    【解决方案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();
    }
    

    【讨论】:

      【解决方案3】:

      如果您的存储过程根据您的问题需要四个参数,您可以将参数添加到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();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-02-07
        • 2014-08-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-09-28
        相关资源
        最近更新 更多