简体   繁体   English

将参数从Excel传递到SQL

[英]Passing parameters from Excel to SQL

ALTER PROCEDURE [dbo].[SP_Hello] 
    @portfolio nvarchar(5), 
    @discount numeric(18,2), 
    @lowerlimit numeric(18,2), 
    @midlimit numeric(18,2)
AS
BEGIN
    SET NOCOUNT ON;

    SELECT distinct 
        EntityDescription, 
        d.AmountDueInCurr * @discount as [1st part],
        d.AmountDueInCurr * (1 - @discount) as [2nd Part], 
        CASE WHEN d.AmountDueInCurr <= 0 THEN 'Solution 1'
             WHEN d.AmountDueInCurr between 0 and @lowerlimit THEN 'Solution 2'
             WHEN d.AmountDueInCurr between (@lowerlimit + 0.01) and @midlimit THEN CONCAT(@portfolio, '-01')
             WHEN d.AmountDueInCurr > (@midlimit+0.01) THEN CONCAT(@portfolio, '-02')
             ELSE 'Error' 
        END AS Solution_type
    FROM 
        T1 d

and I would like to pass parameters from Excel, using VBA as this one: 我想使用VBA作为这一参数从Excel传递参数:

Private Sub CommandButton1_Click()

    Dim Portfolio As String
    Dim Discount As Single
    Dim lowerlimit As Single
    Dim midlimit As Single

    Portfolio = Sheets("Input").Range("B2").Value
    Popust = Sheets("Input").Range("B3").Value
    lowerlimit = Sheets("Input").Range("B4").Value
    midlimit = Sheets("Input").Range("B5").Value

    With ActiveWorkbook.Connections("Hello_data").OLEDBConnection
        .CommandText = "exec SP_Hello '" & Portfolio & "','" & Discount & "','" & lowerlimit & "','" & midlimit & "'"
        ActiveWorkbook.Connections("Hello_data").Refresh
    End With
    Worksheets(2).Activate
End Sub

Seems like no matter what I do (format, declare or Dim the variables/parameters), I always get the conversion data type error in Excel. 似乎不管我做什么(格式化,声明或使变量/参数变暗),我总是在Excel中得到转换数据类型错误。 I have tried everything from String to Double in excel as well as all numerical combinations in SQL, none of the combinations seem to work. 我已经尝试了Excel中从String到Double的所有内容,以及SQL中的所有数字组合,但这些组合似乎都不起作用。

If I pass just the Portfolio parameter (string) which is nvarchar in the database, it goes well. 如果我仅传递数据库中的nvarchar的Portfolio参数(字符串),则运行良好。 As soon as I add a number, or a Date into the combination, conversion errors appear. 在组合中添加数字或日期后,就会出现转换错误。

Your stored proc parameters have numeric data types defined, but your TSQL string built is passing in strings. 您存储的proc参数已定义了数字数据类型,但是您构建的TSQL字符串正在传入字符串。 You need to remove the single quote you are placing around parameters @discount , @lowerlimit and @midlimit . 您需要删除参数@discount@lowerlimit@midlimit周围的单引号。

To see the issue, simply add this code: 要查看此问题,只需添加以下代码:

Dim tsql As String
tsql = "exec SP_Hello '" & Portfolio & "','" & Discount & "','" & lowerlimit & "','" & midlimit & "'"

Print out tsql, and execute it in SSMS. 打印出tsql,并在SSMS中执行它。 You should see the issue right away. 您应该立即看到该问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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