简体   繁体   中英

Passing comma delimited parameter to stored procedure in SQL

If I pass call my stored procedure from T-SQL:

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

in SQL Server Mgmt Studio, it works fine but when I call it from my application it gives me error

Unclosed quotation mark after the character string ''Vijay','Rana',1,0'.

I searched on the google and find this EXEC sp_executesql @FinalQuery but its not working for me

EDIT
I am calling it like

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;
    }

EDIT My complete Store Procedure

-- =============================================          
-- 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 

Well ' is the delimiter so it seems to me your string becomes 'Vijay','Rana',1,0 I think you are mixing strings and numerics in the same "string" what you need to do is pass 'Vijay','Rana','1','0' (a string of strings) and then sort things out inside your procedure. To do this your passed string should be something like ' '' Vijay'',''Rana'',''1'',''0'' '. Depending on how you handle things inside your stored proc you may even need '' '''' Vijay'''',''''Rana'''',''''1'''',''''0'''' '' .Best create a simple proc which just returns the string as a test bed

If you are using c# and asp.net, you should set up your parameters in code rather then building a dynamic sql statement. If you already have the stored procedure setup then I'm not seeing a reason to call a dynamic sql statement and building out the parameters in a string.

Here is a example of a parameterized call to sql with a stored procedure. 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();
}

If your stored procedure takes four parameters as it seems to based on your question, you can add the parameters to a SqlCommand and then execute the command.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM