where clause in VBA doesn't return what I need - sql

I am trying to filter a dataset that I am pulling in from access using VBA, but for some reason this code doesn't return the filtered results.
With BrokerData
.ActiveConnection = BrokerConn
.Source = "SELECT * FROM BP_Closed_Deals WHERE EMM_Name = 'JM' OR 'J-C E';"
.LockType = adLockReadOnly
.CursorType = adOpenForwardOnly
.Open
End With

The following is not valid SQL syntax:
WHERE EMM_Name = 'JM' OR 'J-C E'
You want:
WHERE EMM_Name = 'JM' OR EMM_Name = 'J-C E'
Which can also be expressed with the IN operator:
WHERE EMM_Name IN ('JM', 'J-C E')

Related

i have an error on access database no value given for one or more parameters

'sql = "select * from tblProduct Order by ProductID"
Sql = "SELECT tblProduct.PID, tblProduct.ProductID, tblProduct.ProductName, tblProduct.SubcategoryID, tblProduct.Description, tblProduct.CostPrice, tblProduct.SellingPrice, tblProduct.Discount, tblProduct.VAT, tblProduct.OpeningStock, tblProduct.Pic FROM tbSubcategory INNER JOIN tblProduct ON tbSubcategory.SubcategoryID = tblProduct.SubcategoryID"
.CursorType = adOpenDynamic
.CursorLocation = adUseClient
.LockType = adLockOptimistic
.Open Sql, cn, , adCmdText

VBA Copy SQL Table without Header

I'm try to copy data from SQl-Server to Excel, but the result is include with headers. I want result without headers. Here my code :
ConnectionString = "Provider=SQLOLEDB;SERVER=DWSQL\User;Database=User;Uid=User;Pwd=User;"
If Sheets("Menu").Cells(4, 4) = "SC" Then
SQL = "SELECT * FROM [MVS].[dbo].[trpos_process] where fc = '2' and process = 'ASSEMBLY' and status = 'NEW'"
ElseIf Sheets("Menu").Cells(4, 4) = "MC" Then
SQL = "SELECT * FROM [MVS].[dbo].[trpos_process] where fc = '3' and process = 'ASSEMBLY' and status = 'NEW'" 'and startby is Null"
ElseIf Sheets("Menu").Cells(4, 4) = "EV" Then
SQL = "SELECT * FROM [MVS].[dbo].[trpos_process] where fc = '5' and process = 'ASSEMBLY' and status = 'NEW' and pos_no like 'EN5%'"
End If
Connection.Open ConnectionString
rs.Open SQL, Connection, adOpenStatic, adLockReadOnly
Set QT = ActiveSheet.QueryTables.Add(rs, Sheets("Data").Cells(1, 2))
QT.Refresh: rs.Close: QT.Delete: Connection.Close
Thanks.
Use CopyFromRecordset!
ConnectionString = "Provider=SQLOLEDB;SERVER=DWSQL\User;Database=User;Uid=User;Pwd=User;"
If Sheets("Menu").Cells(4, 4) = "SC" Then
Sql = "SELECT * FROM [MVS].[dbo].[trpos_process] where fc = '2' and process = 'ASSEMBLY' and status = 'NEW'"
ElseIf Sheets("Menu").Cells(4, 4) = "MC" Then
Sql = "SELECT * FROM [MVS].[dbo].[trpos_process] where fc = '3' and process = 'ASSEMBLY' and status = 'NEW'" 'and startby is Null"
ElseIf Sheets("Menu").Cells(4, 4) = "EV" Then
Sql = "SELECT * FROM [MVS].[dbo].[trpos_process] where fc = '5' and process = 'ASSEMBLY' and status = 'NEW' and pos_no like 'EN5%'"
End If
Connection.Open ConnectionString
rs.Open Sql, Connection, adOpenStatic, adLockReadOnly
Range("b2").CopyFromRecordset rs
rs.Close: QT.Delete: Connection.Close

SQL/Server function yielding different result when called from VBS

I have the following SQL/Server function defined in C# to detect when a vehicle has refuelled. I keep a context of the last fuel used so that I don't need to move a cursor back over the data:
[Microsoft.SqlServer.Server.SqlFunction]
public static SqlDouble GetFuelRefill(SqlString ID, SqlString FuelLeft)
{
object _lastID = CallContext.GetData("lastID6");
object _fuelRefill = CallContext.GetData("fuelRefill");
double fuelRefill = _fuelRefill == null ? 0.0 : Convert.ToDouble(_fuelRefill);
object _lastFuelLeft = CallContext.GetData("lastFuelLeft");
double lastFuelLeft = _lastFuelLeft == null ? 0.0 : Convert.ToDouble(_lastFuelLeft);
double result = 0.0;
if ((_lastID == null) || (Convert.ToString(_lastID) != ID.Value) || (_lastFuelLeft == null))
{
fuelRefill = 0;
CallContext.SetData("lastFuelLeft", 0.0);
}
else if (!FuelLeft.IsNull)
{
double fl = Convert.ToDouble(FuelLeft.Value);
if ((fl > 0.0) && (lastFuelLeft > 0.0) && ((fl - lastFuelLeft) / fl * 100.0 >= 5.0))
fuelRefill += fl - lastFuelLeft;
CallContext.SetData("lastFuelLeft", FuelLeft.Value);
}
result = fuelRefill;
CallContext.SetData("lastID6", ID.Value);
CallContext.SetData("fuelRefill", fuelRefill);
return new SqlDouble(result);
}
For the purpose of repeating the problem I have created a small test table:
SequenceNo AssetID FuelLeft
1 PJ1 50
2 PJ1 49
3 PJ1 48
4 PJ1 98
5 PJ1 95
Then I execute the following command from SQL/Server Management Studio:
SELECT SequenceNo,dbo.GetFuelRefill(AssetID,FuelLeft) AS Refill
FROM TestTable ORDER BY SequenceNo
Which yields the following result that I expect:
SequenceNo Refill
1 0
2 0
3 0
4 50
5 50
However then I try executing the same query using ADO from VBScript:
const DatabaseName = "MyDB"
const DatabaseServer = "(local)"
const adOpenForwardOnly = 0
const adLockOptimistic = 3
Dim FSO : set FSO = CreateObject("Scripting.FileSystemObject")
Dim Conn : Set Conn = CreateObject("ADODB.Connection")
Conn.Open "Provider=SQLOLEDB.1;Integrated Security=SSPI;Initial Catalog=" & DatabaseName & ";Server=" & DatabaseServer
Set Query = CreateObject("ADODB.Recordset")
Query.Open "SELECT SequenceNo,dbo.GetFuelRefill(AssetID,FuelLeft) AS Refill FROM TestTable ORDER BY SequenceNo", Conn, adOpenForwardOnly, adLockOptimistic
Set f = FSO.CreateTextFile("E:\Temp\Test.TXT", true)
do while not Query.EOF
f.WriteLine Query("SequenceNo") & ", " & Query("Refill")
Query.MoveNext
loop
Set FSO = Nothing
Query.Close
Conn.Close
The test.txt file contains the following:
1, 0
2, 0
3, 0
4, 0
5, 0
Doing some further debugging it appears that the call context isn't being saved for the duration of the query, but I wondered if anyone knows why and a way to solve it?
After further experimentation I found two solutions. One was to place the query inside a simple stored procedure such as:
CREATE PROCEDURE sp_Test
AS
BEGIN
SET NOCOUNT ON;
SELECT SequenceNo,dbo.GetFuelRefill(AssetID,FuelLeft) AS Refill
FROM TestTable ORDER BY SequenceNo
END
And the other was to change the VBS code to use a client-side cursor:
const DatabaseName = "MyDB"
const DatabaseServer = "(local)"
const adOpenForwardOnly = 0
const adLockOptimistic = 3
const adUseClient = 3
Dim FSO : set FSO = CreateObject("Scripting.FileSystemObject")
Dim Conn : Set Conn = CreateObject("ADODB.Connection")
Conn.Open "Provider=SQLOLEDB.1;Integrated Security=SSPI;Initial Catalog=" & DatabaseName & ";Server=" & DatabaseServer
Set Query = CreateObject("ADODB.Recordset")
Query.CursorLocation = adUseClient
Query.Open "SELECT SequenceNo,dbo.GetFuelRefill(AssetID,FuelLeft) AS Refill FROM TestTable ORDER BY SequenceNo", Conn, adOpenForwardOnly, adLockOptimistic
Set f = FSO.CreateTextFile("E:\Temp\Test.TXT", true)
do while not Query.EOF
f.WriteLine Query("SequenceNo") & ", " & Query("Refill")
Query.MoveNext
loop
Set FSO = Nothing
Query.Close
Conn.Close

Multidimensional array problem

I want to create a multidimensional array with 2 columns and have the row size a dynamic value. I then want to populate the multidimensional array with values from 2 different SQL queries (Microsoft).
The problem is That when the page loads it seems to be empty. How can Fill each column with he two different recordsets?
Or
At least return the total number of rows in the recordset?
Code below -
connectionstring = obj_ADO.getconnectionstring
Set objCon = CreateObject("ADODB.Connection")
Set objRS = CreateObject("ADODB.Recordset")
set objComm = CreateObject("ADODB.Command")
objCon.Open connectionstring
objComm.ActiveConnection = objCon.ConnectionString
objComm.CommandText = "A_Page_Paging"
objComm.CommandType = adCmdStoredProc
Set objParameter = objComm.CreateParameter
objParameter.Name = "selected_Char"
objParameter.Type = adChar
objParameter.Direction = adParamInput
objParameter.Size = 3
objParameter.Value = Selected_Button
objComm.Parameters.Append objParameter
set objRS = objComm.Execute
Increment = 0
Dim testArray()
while not objRS.EOF
Redim testArray(2, increment)
'--------------------------------------------
Page_ID = objRS("P_PageID")
connectionstring = obj_ADO.getconnectionstring
Set objConn = CreateObject("ADODB.Connection")
Set objRSS = CreateObject("ADODB.Recordset")
objConn.Open connectionstring
SQL = "Select P_Name as P_Name, P_Description as P_Description from L_PagePermission inner join A_Permission on p_permissionID = pp_PermissionID inner join A_Page on P_PageID = PP_PageID where P_PageID =" & Page_ID & " order by p_Name"
objRSS.open SQL, objConn
if not objRSS.EOF then
objRSS.MoveFirst
while not objRSS.EOF
'Fill Array
testArray(0, increment) = objRS("P_PageID")
objRSS.MoveNext
wend
objRSS.close
objConn.close
else
testArray(0, increment) = "-"
end if
Increment = Increment + 1
'--------------------------------------------
%>
<%
objRS.MoveNext
wend
objRS.Close
objCon.Close
response.Write testArray(0,5)
Figured it out myself by using preseve in the redim of my array so the code below fixed my problem -
'--------------------------------------------
Increment = 0
Dim testArray()
connectionstring = obj_ADO.getconnectionstring
Set objConn = CreateObject("ADODB.Connection")
Set objRSS = CreateObject("ADODB.Recordset")
objConn.Open connectionstring
SQL = "select * from a_permission inner join L_PagePermission on P_PermissionID = PP_PermissionID inner join A_Page on P_PageID = PP_PageID order by P_Name"
objRSS.open SQL, objConn
if not objRSS.EOF then
objRSS.MoveFirst
while not objRSS.EOF
Redim Preserve testArray(2, increment)
'Two Dimensional Array
testArray(0, increment) = objRSS("P_PageID")
testArray(1, increment) = objRSS("P_Name")
objRSS.MoveNext
Increment = Increment + 1
wend
objRSS.close
objConn.close
else
testArray(0, increment) = "-"
testArray(1, increment) = "-"
end if
'--------------------------------------------
'--------------------------------------------
Page_ID = objRS("P_PageID")
for i = 0 to (increment - 1)
if testArray(0, i) = Page_ID then
%>
<li style="" ="padding:0;margin:0;"><%=testArray(1,i)%></li>
<%
end if
next
'--------------------------------------------
If you run this query, do you get rows returned?
Select P_Name as P_Name, P_Description as P_Description from L_PagePermission inner join A_Permission on p_permissionID = pp_PermissionID inner join A_Page on P_PageID = PP_PageID where P_PageID =" & Page_ID & " order by p_Name

passing parameters into stored procedures classic asp

I've asked a similar question before and although I've attempted to fix my previous code i now end up with an error "Arguments are of the wrong type, are out of acceptable range, or are in conflict with one another". I want to pass a single character as a parameter to query a database then use recordset to print out to a webpage. My classic asp code is below
Set objCon = CreateObject("ADODB.Connection")
Set objRS = CreateObject("ADODB.Recordset")
set objComm = CreateObject("ADODB.Command")
objCon.ConnectionString = "Provider=SQLOLEDB.1;Password=xxxx;Persist Security Info=True;User ID=xxxx;Initial Catalog=Movies;Data Source=xxxx-PC"
objCon.open objCon.ConnectionString
objComm.ActiveConnection = objCon.ConnectionString
objComm.CommandText = "Paging_Movies"
objComm.CommandType = adCmdStoredProc
Set objParameter = objComm.CreateParameter
objParameter.Name = "alphaChar"
objParameter.Type = adChar
objParameter.Direction = adParamInput
objParameter.Value = "a"
objComm.Parameters.Append objParameter
set objRs = objComm.Execute
Also my stored procedure is below -
CREATE PROCEDURE Paging_Movies
#alphaChar char(1)
AS
if #alphaChar = '#'
select * from Movies where movies like '[^a-z]%'
else
select * from Movies where movies like #alphaChar + '%'
Perhaps you're adding the parameter twice. Try to replace:
objComm.ActiveConnection = objCon.ConnectionString
objComm.CommandText = "Paging_Movies"
objComm.CommandType = adCmdStoredProc
Set objParameter = objComm.CreateParameter
objParameter.Name = "alphaChar"
objParameter.Type = adChar
objParameter.Direction = adParamInput
objParameter.Value = "a"
Set objParameter = objCommand.CreateParameter ("alphaChar", adChar, _
adParamInput, "a")
objComm.Parameters.Append objParameter
with just:
objCommand.CreateParameter ("alphaChar", 129, 1, 1, "a")
Edited as your comment suggests to use the numeric values for adChar (129) and adParamInput (1) from the W3Schools CreateParameter page.