将SQL函数结果显示到msgbox中的问题

时间:2018-09-30 21:31:51

标签: sql vbscript

我有一个SQL函数,该函数接受1个输入并返回varchar结果。在SSMS中执行时,此方法工作正常,但是当我尝试从VBScript中显示时,运行时错误类型不匹配。我打算使用此变量来检索代码另一部分中的其他数据。我只是在使用显示器来可视化我收到的内容并帮助我了解自己在做什么。

SQL函数:

ALTER FUNCTION [dbo].[ufnGetLongModelFromSerial] (@serial varchar(8)) returns varchar(30)

AS

BEGIN
  RETURN (SELECT LongModel
  FROM [dbo].[Compressor], [dbo].[Models]
  WHERE [Compressor].[Serial] = @serial AND [dbo].[Compressor].[Model] = [dbo].[Models].[Model])
END
GO

--print result of function for testing
DECLARE @serial varchar(8) = '18HE3712'
PRINT [dbo].[ufnGetLongModelFromSerial] (@serial)

VBScript:

Option Explicit

'see http://www.w3schools.com/ado/ado_datatypes.asp
Const adParamInput = 1
Const adParamOutput = 2
Const adParamInputOutput = 3
Const adParamReturnValue = 4

Const adVarChar = 200

Const sSourceServer = "myserver"
Const sSourceDB = "myDB"

Dim connstr
Dim cmd
Dim SP_Name
Dim serial
Dim longModel

SP_Name = "ufnGetLongModelFromSerial"
connstr = "Provider=SQLOLEDB;Data Source=" & sSourceServer & "; Initial Catalog=" & sSourceDB & ";User Id=myid; Password=mypassword;"

Set serial = CreateObject("ADODB.Parameter")
serial.Direction = adParamInput
serial.Name = "serial"
serial.Size = 30
serial.Type = adVarChar
serial.Value = "18HD0363"

'set up sql command object
Set cmd = CreateObject("ADODB.Command")
With cmd
  .ActiveConnection = connstr
  .CommandType = 4
  .CommandText = SP_Name
  .Parameters.Append serial
End With

'execute command object and set local variable longModel to equal result of select statement in stored procedure
longModel = cmd.Execute

Wscript.Echo longModel
'tidy up and remove objects
Set serial = Nothing
Set cmd = Nothing

1 个答案:

答案 0 :(得分:0)

作为cmd.Execute返回Recordset对象,您应该编写

WScript.Echo longModel(0)

另请参见

VBScript - Retrieving a Scalar Value From a Stored Procedure on SQL Server 2008