Excel VBA connection to SQL stored procedure with parameters

时间:2019-04-08 13:32:48

标签: sql excel vba stored-procedures

I´m creating an excel with connection to a database that will execute a stored procedure and return the result. This stored procedure has certain parameters, filters that the user can use to define the query/search.

This is my variables in excel that correspond to the stored procedure, there are no mistypematches and no sort of error, except when I enter a filter it doesn't show any result even if it exists.

This is my excel variables that read the value that is in the corresponding cell.

Dim area, n_bem, desc, marca, classe As String

  Range("A2").Select
  n_bem = CStr(ActiveCell.Value)

  Range("B2").Select
  desc = CStr(ActiveCell.Value)

  Range("C2").Select
  marca = CStr(ActiveCell.Value)

  Range("D2").Select
  classe = CStr(ActiveCell.Value)

  Range("I2").Select
  area = CStr(ActiveCell.Value)

  (...)

 .CommandText = " exec " + StoredProcedure + "'%" + n_bem + "%'" + "," + "'%" + desc + "%'" + "," + "'%" + marca + "%'" + "," + "'%" + classe + "%'" + "," + "'" + area + "'"

In my SQL, I have the following stored procedure, in case the cell is empty should write "%" so that it can show all.

@area varchar(20) = "11",
@n_bem varchar(20) = "%",
@desc varchar(20) = "%",
@marca varchar(20) = "%",
@classe varchar(20) = "%"

and the "where" clause:

  WHERE
  and e.[Dimension Value Code] = @area
  and a.[No_] LIKE @n_bem
  and [Description] LIKE @desc
  and [Marca_Fabricante] LIKE @marca
  and b.[Name] LIKE @classe
  order by a.[No_] desc

The problem is whenever i run the code with a button in SQL spreadsheet and applied a filter it doesn't show any results.

0 个答案:

没有答案