VBScriptで文字列をuniqueidentifierに変換します
-
19-08-2019 - |
質問
SQLサーバーデータベースでストアドプロシージャを実行するスクリプトがあります。問題は、ストアドプロシージャがuniqueidentifierパラメーターを使用することです。データベース(nvarchar)からセッションIDを取得する関数があるため、VBScriptはそれを文字列にし、ストアドプロシージャに渡すために変換する必要があります。
Function GetOpenSession
Set conn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
conn.Open "Provider=SQLOLEDB.1;Integrated Security=SSPI;Data Source=" & Source
rs.CursorLocation = 3
rs.Open "SELECT top 1 OpenSession FROM OpenSessions with (nolock)" , conn, 3, 3
If rs.RecordCount = 0 Then
MsgBox "No Connection"
Else
GetOpenSession = rs.Fields(0).Value
End If
End Function
<!> quot;キャスト仕様の無効な文字値<!> quot;ストアドプロシージャを実行しようとしたとき。
set cnParam = cmd.CreateParameter("@ActiveSession",72,1,,GetOpenSession)
cmd.Parameters.Append cnParam
データベース内では何も変更できないため、スクリプトでこれを克服する方法が必要です。
解決
Depending on the data type of the SELECT OpenSession, you may be able to cast/convert it in the query and VBScript may possibly keep the data type as a GUID:
SELECT top 1 CONVERT(uniqueidentifier, OpenSession)
FROM OpenSessions with (nolock)
When you use GetOpenSession
or rs.Fields(0).Value
, hopefully VBScript will keep it as a GUID.
The other possibility seems to be a Win32 API using CoCreateGuid
and StringFromGUID2
. An example is found here, but it requires external Win32 functions and a Type for GUID.
他のヒント
I believe VBScript expects GUIDs to be brace terminated. Is your Session id of the same format as the following {D6CA6263-E8E1-41C1-AEA6-040EA89BF030}
I usually change the parameter type of the stored procedure to varchar(38).
SQL Server makes a better job of coercing the string to a GUID when needed.
What is the value of GetOpenSession after you have assigned it? Which datatype? It sounds like it is not compatible with type 72 (GUID), which you are stating in the CreateParameter call.
You could forget about using ADO Commands altogether and just execute the stored procedure using plain SQL.
Set rs = CreateObject("ADODB.Recordset")
rs.Open "EXEC usp_MySP '" & GetOpenSession & "'", cnn
Obviously it's terrible to build SQL commands like this, but it's just for a test, after all...