Can't access output variable in command text - tsql

Set cmd = Server.CreateObject("ADODB.Command")
With cmd
.ActiveConnection = db
.CommandText = "SELECT #date = '2019-01-01'"
.Parameters.Append(.CreateParameter("#date", adDBDate, adParamOutput))
.Execute
End With
Gives...
Must declare the scalar variable "#date".
Why can't I access the output parameter in the query text?

Named parameters work as expected on both sides (Server: SQL Server, Client: ADODB & VBScript for your case) only if the provider supports it. For SQL Server providers it is supported only with commands configured to call a stored procedure with named parameters (where cmd.CommandType set adCmdStoredProc and cmd.NamedParameters set True).
For an ordinary command like yours, named parameters are not recognized by the server, only the ? placeholders recognized as parameters in the query.
So you should try something like the following.
Set cmd = Server.CreateObject("ADODB.Command")
With cmd
.ActiveConnection = db
.CommandText = "SELECT ? = '2019-01-01'"
.Parameters.Append(.CreateParameter("#dummyForServerNotForClient", adDBDate, adParamOutput))
.Execute
' must print: 2019-01-01
Response.Write .Parameters("#dummyForServerNotForClient").Value
End With
Since the parameter names ignored by servers, you can write the same code by omitting the parameter name, and access the parameter's value by using its ordinal position in the collection. IMHO, with the lack of explicitly named parameters the code becomes more logical and readable.
Set cmd = Server.CreateObject("ADODB.Command")
With cmd
.ActiveConnection = db
.CommandText = "SELECT ? = '2019-01-01'"
.Parameters.Append(.CreateParameter(, adDBDate, adParamOutput))
.Execute
' also must print: 2019-01-01
Response.Write .Parameters(0).Value
End With
I hope this helps you to understand the concept.

The error comes from T-SQL because the variable #date hasn't been declared.
Adjust the T-SQL string you are passing into the ADODB.Command to declare the variable;
Set cmd = Server.CreateObject("ADODB.Command")
With cmd
.ActiveConnection = db
.CommandText = "DECLARE #date AS DATETIME; SELECT #date = '2019-01-01';"
.Parameters.Append(.CreateParameter("#date", adDBDate, adParamOutput))
.Execute
End With
A simple way to debug these types of issues is to use the SQL Server Management Studio to run the query raw.
SELECT #date = '2019-01-01'
If you had tried to run the query without the declaration you would have got the same error with a bit more detail.
Msg 137, Level 15, State 1, Line 1
Must declare the scalar variable "#date".

Related

Access pass-through query with parameters not updating with prompted parameters

An Access pass-through query works when using the default parameters. When used in an Access report, the prompts that are used returns records based on the default parameters in the ptq and not the answered prompts. Default data is being returned.
I have a SQL Server based stored procedure that works, uspWorkCentreReport, that uses #TheDate DATE, #WC VARCHAR(15), #Shift INT for parameters and returns, through a SELECT statement, these columns:
[JOB NUMBER], [REL #], [JOB NAME], QTY.
Here's the ALTER line of the stored procedure code:
ALTER PROCEDURE [dbo].[uspWorkCentreReport]
#TheDate DATE,
#WC VARCHAR(15),
#Shift INT
The Access pass-through query, ptq_uspWorkCentreReport, passes these default parameters '2019-05-30','PCOT',1 and uses a DSN-less ODBC connection that works to return default data. I forgot to try but I think it will return correct data with whatever default parameters I use to replace '2019-05-30','PCOT',1. EDIT - I tried it this morning and indeed any appropriate replacement parameters return the appropriate associated records. Here's the ptq's one line:
exec uspWorkCentreReport '2019-05-30','PCOT',1
I provide the ptq with default parameters based on Albert D. Kallal's SO reply.
I use an Access select query, qry_ptq_uspWorkCentreReport, to receive [JOB NUMBER],[REL #],[JOB NAME],QTY and pass the parameters TheDate, set to Date With Time, WC, set to Short Text, and Shift, set to Integer.
qry_ptq_uspWorkCentreReport uses the pass-through query. The parameters are set using Access' Parameters applet and not within the query fields. Running this select query prompts for the 3 parameters but only returns data based on the default parameters set in the ptq's one line. I did not think to look at the Access SQL statement but will do so when I get to work tomorrow morning. EDIT - Here's the SQL statement for qry_ptq_uspWorkCentreReport:
PARAMETERS TheDate DateTime, WC Text ( 255 ), Shift Short;
SELECT ptq_uspWorkCentreReport.[JOB NUMBER], ptq_uspWorkCentreReport.[REL #], ptq_uspWorkCentreReport.[JOB NAME], ptq_uspWorkCentreReport.QTY
FROM ptq_uspWorkCentreReport;
Of course the above three functions culminate in an Access report, rpt_qry_ptq_WorkCentreReport to make the records human readable.
I have used the same scenario for another report the takes From and To dates as parameters. When that report runs, the prompts take the dates and return records based on those dates and not the dates in the ptq. Here's that ptq:
exec uspMergeAandPJobs '2018-01-01','2019-01-01'
Indeed, I tried using
exec uspMergeAandPJobs '',''
And the report returns 0 records!
Not sure what I am missing and would appreciate any feedback. TIA.
I tried the following with the help of a tutor:
Sub Report_Load()
Dim strFromDate As String
Dim strToDate As String
Dim strWC As String
Dim intShift As Integer
Dim strSQL As String
strFromDate = InputBox("From Date and Time: ")
strToDate = InputBox("Enter To Date and Time: ")
strWC = InputBox("Enter Work Center: ")
intShift = InputBox("Enter Shift: ")
Dim qdf As DAO.QueryDef, rst As DAO.Recordset
Set qdf = CurrentDb.CreateQueryDef("")
qdf.SQL = "exec dbo.uspWorkCentreReport " & "'" & strFromDate & "', " & "'" & strToDate & "', " & "'" & strWC & "', " & intShift & ";"
qdf.Connect = "ODBC;DRIVER=ODBC Driver 13 for SQL Server;SERVER=OURS\NTSQL;Trusted_Connection=Yes;DATABASE=TablesCoE;ApplicationIntent=READONLY;"
qdf.ReturnsRecords = True
Set rst = qdf.OpenRecordset
rst.Close
Set rst = Nothing
Set qdf = Nothing
End Sub
After the prompts VBA spits up a Run-Time error 3129 - Invalid SQL statement; expected 'DELETE', 'INSERT', 'PROCEDURE', 'SELECT', or 'UPDATE'. Neither of us were able to determine what was causing the error. In VBA the "qdf.SQL..." line is highlighted in yellow.
EDIT - Adding stored proc's SQL code:
ALTER PROCEDURE [dbo].[uspWorkCentreReport_TEST] #FromDate DATETIME,#ToDate DATETIME,#WC VARCHAR(15),#Shift INT
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Build table variable SumTable structure
DECLARE #SumTable TABLE(matl_nbr VARCHAR(60),QTY DECIMAL(4,0),matl_dsc VARCHAR(50))
-- P jobs and their summed WorkCentre traversals using crosstab - each traversal is added up
INSERT INTO #SumTable(matl_nbr,matl_dsc,QTY)
SELECT SRC1.matl_nbr,SRC1.matl_dsc,
SUM(CASE WHEN SRC1.locn_to = #WC THEN 1 ELSE 0 END) AS QTY
FROM
(
SELECT matl_nbr,matl_dsc,locn_to
FROM mtrk_CompanyE.dbo.trxn_hstd th
WHERE (last_upd >= #FromDate AND last_upd <= #ToDate) AND
locn_to = #WC
)SRC1
GROUP BY matl_nbr,matl_dsc
-- These updates take all the summed WorkCentre (locn_to) columns and turn each into "1" for later summing
UPDATE #SumTable
SET QTY = 1
WHERE QTY >1
-- Shortening the material number from 123456_00_00_R1_00 to 1234560
UPDATE #SumTable
SET matl_nbr = LEFT(matl_nbr,6) + right(LEFT(matl_nbr,9),1)
SELECT LEFT(A.matl_nbr,6)[JOB NUMBER],SUBSTRING(A.matl_nbr,7,1)[REL #],matl_dsc AS [JOB NAME],QTY
FROM (SELECT matl_nbr,matl_dsc,
SUM(CASE WHEN QTY = 1 THEN 1 ELSE NULL END) AS QTY
FROM #SumTable
GROUP BY matl_nbr,matl_dsc)A
ORDER BY QTY DESC;
END
EDIT - Finished sub:
Private Sub Report_Open(Cancel As Integer)
Dim strFromDate As String
Dim strToDate As String
Dim strWC As String
Dim intShift As Integer
Dim strSQL As String
strFromDate = InputBox("Enter From Date and Time: ")
strToDate = InputBox("Enter To Date and Time: ")
strWC = InputBox("Enter Work Center: ")
intShift = InputBox("Enter Shift: ")
strSQL = "exec dbo.uspWorkCentreReport_TEST " & "'" & strFromDate & "', " & "'" & strToDate & "', " & "'" & strWC & "', " & intShift & ";"
CurrentDb.QueryDefs("ptq_uspWorkCentreReport").SQL = strSQL
DoCmd.OpenReport "rpt_qry_ptq_uspWorkCentreReport", acViewReport
Me.lblFromDate.Caption = strFromDate
Me.lblToDate.Caption = strToDate
Me.lblWC.Caption = strWC
Me.lblShift.Caption = intShift
End Sub
Your Access query has parameters:
PARAMETERS TheDate DateTime, WC Text ( 255 ), Shift Short;
and since they are defined in the query definition, Access asks for them when opening/running the query.
But these parameters are never used!
There is no way for Access to pass these parameters into the pass-through query that is the basis of the Access query. Again, a PT query is nothing more than a Connect string and a constant SQL string.
So when you run the Access query, it will always run the saved contents of the PT query, i.e.
exec uspWorkCentreReport '2019-05-30','PCOT',1
The parameters you entered are ignored.
What you need to do (as outlined in the answer you refer to):
create a form to collect the parameter values
dynamically create the SQL string for the PT query with VBA
assign that SQL to the PT query:
CurrentDb.QueryDefs("ptq_uspWorkCentreReport").SQL = strSql
(it is automatically saved)
and then you can run the report based on the Access query - or better: directly use the PT query as record source for the report.
Remove the parameters from the Access query, they are of no use for your situation. Or remove the query entirely, unless you need it to join the PT query with something else.
Edit for above edit:
If you get a runtime error, there is probably a syntax error in your .Sql. Build the SQL string in a variable, do Debug.Print strSql, and run that string in SSMS. You may need to change date formatting (depending on your locale settings).
Also: See my 3rd bullet. Defining a temporary querydef and opening a recordset doesn't work for a report. You must assign the .Sql of the existing query that is the record source of the report.
Addendum: if you need to create a new query, first set .Connect, and then .Sql, so Access knows it's a Pass-Through query.
Access SQL doesn't know exec.
Edit 2
You have an existing, working PT query ptq_uspWorkCentreReport, which returns records for one set of parameters, e.g.
exec uspWorkCentreReport '2019-05-30','PCOT',1
Use this query as record source for your report.
To run the report with different parameters, you must modify the query's SQL. You can do this manually in query design view, or with VBA.
I think Report_Load() is too late for modifying its record source (the PT query). Run the following sub, then open the Report.
Sub SetUspParameters()
Dim strFromDate As String
Dim strToDate As String
Dim strWC As String
Dim intShift As Integer
Dim strSQL As String
strFromDate = InputBox("From Date and Time: ")
strToDate = InputBox("Enter To Date and Time: ")
strWC = InputBox("Enter Work Center: ")
intShift = InputBox("Enter Shift: ")
strSQL = "exec dbo.uspWorkCentreReport " & "'" & strFromDate & "', " & "'" & strToDate & "', " & "'" & strWC & "', " & intShift & ";"
Debug.Print strSQL
' This line is all that's needed to modify the PT query
CurrentDb.QueryDefs("ptq_uspWorkCentreReport").SQL = strSQL
End Sub
In practice, you don't want to use 4 x InputBox, but a form.

Calling Table Valued Function from Visual Basic 6

I have some legacy code that I need to update, and I need to add a feature that uses the value returned from a table valued function. The issue I am having is that the function returns a table variable. The function is something like follows:
CREATE FUNCTION [dbo].[SomeFunction](#intKey INT)
RETURNS #t TABLE (strValue VARCHAR(20))
BEGIN
(....SOME CODE.....)
INSERT INTO #t (strValue) SELECT #SomeValue
RETURN
END
The code I call the function from VB is as follows:
Dim objRS As New ADODB.Recordset
Dim objCmd As New ADODB.Command
Set objRS = New ADODB.Recordset
With objCmd
.ActiveConnection = objConnection.CurrentConnection
.CommandType = adCmdText
.CommandText = "SELECT * FROM [dbo].[SomeFunction](?)"
.CommandTimeout = 0
End With
objCmd.Parameters.Append objCmd.CreateParameter("#intKey", adInteger, adParamInput)
objCmd("#intMatterID") = someObject.Key
Set objRs = objCmd.Execute
If (objRs.RecordCount > 0) Then
someString = objRs.Fields("strValue")
End If
The problem seems to be that last block of code, and I have confirmed that the Recordset is not empty. The Fields value seems to always be a NULL.
So I assume that I am doing this incorrectly and was wondering if it was possible to retrieve the value of "strValue".
It seems the issue I was experiencing was related to how I was accessing "strValue". I implemented the following and it ended up working.
If (objRs.RecordCount > 0) Then
objRs.MoveFirst
someString = Cstr(objRs("strValue"))
End If

Is there a way to get the full command text of an NpgsqlCommand?

With code like this:
string strCommand = "SELECT * FROM \"MyDataBase\".\"vwUsers\" "
strCommand += "WHERE name LIKE '%' || :name || '%' ";
strCommand += "ORDER BY name ASC LIMIT :page_limit OFFSET :row_offset";
NpgsqlCommand cCommand = new NpgsqlCommand(strCommand);
cCommand.Parameters.Add(new NpgsqlParameter("name", NpgsqlDbType.Text));
cCommand.Parameters[0].Value = strName;
cCommand.Parameters.Add(new NpgsqlParameter("page_limit", NpgsqlDbType.Integer));
cCommand.Parameters[1].Value = nPageAmount;
cCommand.Parameters.Add(new NpgsqlParameter("row_offset", NpgsqlDbType.Integer));
cCommand.Parameters[2].Value = nRowOffset;
Is there a way to get the full text of the command string with all the parameters plugged into it?
Nope. The reason for this is that since Npgsql 3.0 parameters aren't simply substituted in the string; Npgsql actually sends your SQL with parameter placeholders, and transmits the parameters in a separate message and in binary encoding. In other words, there's no point anywhere at which the SQL query is available as text with the parameters.
(Note: in Npgsql 2.2 client-side parameter binding was done for non-prepared messages, so this was in theory possible).
try this cCommand.CommandText
reference Npgsql.NpgsqlCommand

T-SQL CTE + classic asp - which CommandType to use?

I have a CTE statement. When I try to execute in with classic asp the parameter is not replaced correctly:
Set cmd=Server.CreateObject("ADODB.Command")
cmd.ActiveConnection = objConnection
cmd.CommandText = " my CTE is here"
cmd.CommandType = adCmdText
'adCmdUnspecified,adCmdText,adCmdTable,adCmdStoredProc,adCmdUnknown,adCmdFile,adCmdTableDirect
Set objParam = cmd.CreateParameter(, adBigInt , adParamInput ,8,CLng(MyParameter))
cmd.Parameters.Append objParam
When I get the final statement the "?" is not replace in the statement and it gives me error.
I try with each command type but no results.
The issue was caused by foolish syntax error in the "CommandText" string.

How do I insert data into a Postgres table using PowerShell or VBScript?

I need to periodically query the event logs on a handful of servers and insert specific events into a Postgres table.
I am having trouble figuring out how I can insert data into a table via ODBC using PowerShell and/or VBScript. I'm reasonably familiar with both VBScript and PowerShell generally, and I can craft a SQL UPDATE statement that works, I'm just trying to tie the two together, which I've never done before.
I have the Postgres ODBC driver installed, I've configured a data source which tests OK.
Google isn't helping me thus far, can someone provide some pointers?
What part are you having trouble with? How far have you got? Do you have a connection open? Do you know the syntax of the connection string?
Prepare a connection:
Set conn = Server.CreateObject("ADODB.Connection")
conn.Open dsn, dbuser, dbpass
insert:
insert = "insert into table (col1, col2) values (12, 'Example Record')"
conn.Execute insert
If conn.errors.Count > 0 Then
Dim counter
WScript.echo "Error during insert"
For counter = 0 To conn.errors.Count
WScript.echo "Error #" & DataConn.errors(counter).Number
WScript.echo " Description(" & DataConn.errors(counter).Description & ")"
Next
Else
WScript.echo "insert: ok"
End If
for completeness, query:
query = "select * from table where col1 = 7"
Set recordSet = conn.execute(query)
' result is an object of type ADODB.RecordSet
If you want powershell, try this post.
If you need to know the connection string, try connectionstrings.com.
Thanks for the response.
I used more Googling and eventually grokked enough ADO.NET to get it working, although it may not necessarily be "correct".
$DBConnectionString = "Driver={PostgreSQL UNICODE};Server=$DBIP;Port=$DBPort;Database=$DBName;Uid=$DBUser;Pwd=$DBPass;"
$DBConn = New-Object System.Data.Odbc.OdbcConnection
$DBConn.ConnectionString = $DBConnectionString
$DBCmd = $DBConn.CreateCommand()
[void]$DBCmd.Parameters.Add("#TimeStamp", [System.Data.Odbc.OdbcType]::varchar, 26)
[void]$DBCmd.Parameters.Add("#ErrorText", [System.Data.Odbc.OdbcType]::varchar, 4000)
$DBCmd.CommandText = "INSERT INTO errorinfo (errortime,xml) VALUES(?,?)"
$DBCmd.Connection.Open()
$DBCmd.Parameters["#TimeStamp"].Value = $TimeStamp.ToString("yyyy-MM-dd HH:mm:ss")
$DBCmd.Parameters["#ErrorText"].Value = $ErrorText
[void]$DBCmd.ExecuteNonQuery()