ERROR: The conversion of string " Declare #RepInt=" to double is not valid - sql-server

I have this query
Dim count as integer = 4
Dim sql As String = " DECLARE #rep INT = " + count + "; " + _
" WITH cte AS " + _
" ( " + _
" SELECT TOP (#rep) " + _
" ROW_NUMBER() OVER (ORDER BY (SELECT 1)) AS N " + _
" FROM sys.All_Columns ac1 " + _
" CROSS JOIN sys.ALL_Columns ac2 " + _
" ) " + _
" SELECT t.Barcode" + _
" FROM A_Documents t " + _
" CROSS JOIN cte " + _
" where idDocument = 'doc-123456' " + _
" ORDER BY t.Barcode desc; "
If I put a number without a var, ist works:
Dim sql As String = " DECLARE #rep INT = 4; " + _
But when I put my COUNT var, is not work:
Dim sql As String = " DECLARE #rep INT = " + count + "; " + _
And appears this error message:
The conversion of string " Declare #RepInt=" to double is not valid

that's the expected behaviour of the + operator.
when you feed a number variable to it then the system attempts to convert all the other objects to that numeric type to complete the addition, hence the exception.
imho this is a feature because allows you to exactly know what you are concatenating.
the solution:
Dim sql As String = " DECLARE #rep INT = " + count.ToString + "; " + _

When you try to add a string and a number, it will try to convert the string to a number. You can use the & operator instead, which will convert anything that isn't a string to a string:
Dim sql As String = " DECLARE #rep INT = " & count & "; " + _

Related

Pass Array Into Subroutine for Excel VBA?

I'm trying to pass the results of an array into a subroutine. I have an array that picks up four different Buyer codes from a list. They're labelled as BuyOne, BuyTwo, BuyThree, BuyFour. I'm trying to get the results into the next subroutine, but I'm getting a type mismatch at the subroutine call. Even when I fiddle with it I don't know how to get the results into the subroutine. Can anyone tell me what i'm doing wrong?
Code below:
lastRow = Range("O" & Rows.Count).End(xlUp).Row
Set rBuyerList = Range("O1:O" & lastRow)
arrBuyer = Array("BuyOne", "BuyTwo", "BuyThree", "BuyFour")
For i = 0 To UBound(arrBuyer)
With Application
chkFind = .IfError(.Match(Range(arrBuyer(i)), Range("O1:O50"), 0), 0)
End With
If Range(arrBuyer(i)) = vbNullString Or chkFind = False Then
MsgBox "Invalid Buyer Code.." & arrBuyer(i)
Range(arrBuyer(i)).Select
End If
Next i
Call runFinished(sFrDt, sToDt, arrBuyer())
Sheets("Main Sheet").Select
MsgBox ("done...")
End Sub
Sub runFinished(sFrDt As String, sToDt As String, arrBuyer() As Variant)
Dim SQL As String
' add a new work sheet
ActiveWorkbook.Worksheets.Add
' dispay Criteria
Cells(1, 1) = "Run Date: " & Now()
Call MergeLeft("A1:B1")
Cells(2, 1) = "Criteria:"
Cells(2, 2) = "From " & Range("reqFrDT") & " -To- " & Range("reqToDt")
' SQL
SQL = "select a.StockCode [Finished Part], a.QtyToMake, FQOH,FQOO,/*FQIT,*/FQOA, b.Component [Base Material], CQOH,CQOO,CQIT,CQOA " & _
"from ( " & _
" SELECT StockCode, sum(QtyToMake) QtyToMake " & _
" from [MrpSugJobMaster] " & _
" WHERE 1 = 1 " & _
" AND JobStartDate >= '" & sFrDt & "' " & _
" AND JobStartDate <= '" & sToDt & "' " & _
" AND JobClassification = 'OUTS' " & _
" AND ReqPlnFlag <> 'I' AND Source <> 'E' Group BY StockCode " & _
" ) a " & _
"LEFT JOIN BomStructure b on a.StockCode = b.ParentPart " & _
"LEFT JOIN ( " & _
" select StockCode, sum(QtyOnHand) FQOH, Sum(QtyAllocated) FQOO, Sum(QtyInTransit) FQIT, Sum(QtyOnOrder) FQOA " & _
" from InvWarehouse " & _
" where Warehouse in ('01','DS','RM') " & _
" group by StockCode " & _
") c on a.StockCode = c.StockCode " & _
"LEFT JOIN ( " & _
" select StockCode, sum(QtyOnHand) CQOH, Sum(QtyAllocated) CQOO, Sum(QtyInTransit) CQIT, Sum(QtyOnOrder) CQOA " & _
" from InvWarehouse " & _
" where Warehouse in ('01','DS','RM') " & _
" group by StockCode " & _
") d on b.Component = d.StockCode "
SQL = SQL & _
"LEFT JOIN InvMaster e on a.StockCode = e.StockCode " & _
"WHERE 1 = 1 " & _
"and e.Buyer in ('" & BuyOne & "','" & BuyTwo & "','" & BuyThree & "','" & BuyFour & "') " & _
"ORDER BY a.StockCode "
If you have this line in your code
arrBuyer = Array("BuyOne", "BuyTwo", "BuyThree", "BuyFour")
Proper call should be
Call runFinished(sFrDt, sToDt, arrBuyer)
And proper declaration of the function is
Sub runFinished(sFrDt As String, sToDt As String, arrBuyer As Variant) without ()
Edit (Thanks to #Rory)
Previously stated is true if arrBuyer was not declared as follows: dim arrBuyer() as variant or dim arrBuyer(). On the other hand if declaration was dim arrBuyer() 'as variant OP's code would work w/o any changes.
Final note: I still prefer not using arrBuyer() As Variant in the sub declaration.

Varchar to Numeric Exception

I realize this has been asked a million times, but I can't find an answer that works. New to sql server and vs 2010 vb (complain to the boss, not me), doing practice runs. Continually getting a varchar to numeric exception in the following:
Dim height, width As Decimal
height = InputBox("Enter height:")
width = InputBox("Enter width:")
'PRODUCING VARCHAR TO NUMERIC EXCEPTION
command = New SqlCommand("DECLARE #height as decimal(10,2), " & _
"#width as decimal(10,2), " & _
"#area as decimal(10,2); " & _
"SET #height = ' " & height & " '; " & _
"SET #width = ' " & width & " '; " & _
"SET #area = #height * #width; " & _
"IF #height IS NULL OR #width IS NULL " & _
" SELECT 'Either the height or width field was blank.' " & _
"ELSE IF #height <= 0 OR #width <= 0 " & _
" SELECT 'That''s some fancy negative space.' " & _
"ELSE " & _
" SELECT 'The area is: ' +#area;" _
, connect)
connect.Open()
rdr = command.ExecuteReader()
I have verified via vartype() that the data being passed is indeed decimal (I'm the only one testing, so not worried about that error control atm). I have tried using the variables with and without the enclosing single quotes. Cast() and Convert() are not working (unless I'm doing them incorrectly?). Not sure where the problem is?
Dim height, width As Decimal
height = InputBox("Enter height:")
width = InputBox("Enter width:")
'PRODUCING VARCHAR TO NUMERIC EXCEPTION
command = New SqlCommand("IF #height IS NULL OR #width IS NULL " & _
" SELECT 'Either the height or width field was blank.' " & _
"ELSE IF #height <= 0 OR #width <= 0 " & _
" SELECT 'That''s some fancy negative space.' " & _
"ELSE " & _
" SELECT 'The area is: ' + cast(#width * #height as varchar(20))" _
, connect)
command.Parameters.Add("#height", SqlDbType.Decimal).Value = height
command.Parameters.Add("#width", SqlDbType.Decimal).Value = width
connect.Open()
rdr = command.ExecuteReader()
Also, it's very strange to write IF/ELSE statements in SQL to choose among various selects. For SQL, you want to think in terms of writing a single statement that describes a set of data.

aClassic ASP : How to locate an specific order in array, or record-set. Then move Next or Previous, starting from that order

I have done a bit of work on my code, and still unsure about how some of the code needs to be done in order to work.
So far I got a function named FunctionUp' coded, this is the code that will go in the following sequence:
If array of orders contains:
'A1G722
'A1G723
'A1G724
'A1G725
'A1G726
'A1G727
I added a reference to the current location as a query-string parameter named rowindex, so if the order passed in query-string is 'A1G725', the row index value will be 4, then function code will ideally browse in this sequence: 'A1G725', 'A1G724', 'A1G723', 'A1G722'
The code for the button:
.Write "<input type='submit' name='btnUp' value='Next' class='buttonRight' />"
The code that calls the function:
If Request("btnUp") = "Next" Then Call FuctionUp()
The code for the function:
Function FuctionUp()
Dim objConn
Dim objRS
Dim SQLOrderList
Dim SQLCurrentOrder
Dim currentorder
Dim previousorder
Dim sortby
Dim dtstart
Dim dtend
Dim index
currentorder = Trim(Request.QueryString("order"))
sortby = Request.QueryString("sortby")
currentorder = Request.QueryString("order")
dtstart = Request.QueryString("start")
dtend = Request.QueryString("end")
Set objRS = Server.CreateObject("ADODB.Recordset")
Set objConn = CreateObject("ADODB.Connection")
objConn.Open Application("conn_AWDSTAGE")
objRS.Cursortype = 3
SQLOrderList = "SELECT orderno" & _
" FROM _order" & _
" WHERE order_date >= '" & dtstart & "'" & _
" AND order_date < '" & dtend & "'" & _
" ORDER BY " & sortby
objRS.Open SQLOrderList, objConn
index = CINT(Request.QueryString("rowindex"))
If Not isNumeric(index) Or index = "" Then
index = 0
End If
'Get this to Array.
Dim iArray
Dim i
Dim sizeOfiArray
iArray = objRS.GetRows()
' sample of array contents after sql execution
'A1G722
'A1G723
'A1G724
'A1G725
'A1G726
'A1G727
sizeOfiArray = uBound(iArray) + 1
if not index >= (sizeOfiArray - 1) then previousorder = (index + 1)
If Not previousorder Is Nothing Then
Response.Redirect("~/printpreview.asp?order=" & previousorder(i) &
"&site=" & spiderSiteKey &
"&env=" & strEnv &
"&start=" & CDate(dtstart) &
"&end=" & CDate(dtend) &
"&rowindex=" & (index + 1) &
"&sortby=" & sortby)
Else
Response.Redirect("~/printpreview.asp?order=" & currentOrder.OrderID &
"&site=" & spiderSiteKey &
"&env=" & strEnv &
"&start=" & CDate(dtstart)) &
"&end=" & CDate(dtend) &
"&rowindex=" & (index) &
"&sortby=" & strSortBy &
"&LastRecord=Up")
End If
objRS.Close()
Set objRS = Nothing
objConn.Close()
Set objConn = Nothing
End Function
Wouldn't it be easier simply to get the next or previous orders directly from the database using SQL:
sSQLGetPrevOrder = "SELECT top(1) PREV.* " _
& " FROM [Order] PREV " _
& " JOIN ( " _
& " SELECT " & strOrderBy & " sortvalue, orderno " _
& " FROM Order WHERE orderno='" & strCurrentOrder & "' " _
& " ) CURR " _
& " ON PREV." & strOrderBy & " < CURR.sortvalue " _
& " OR ( PREV." & strOrderBy & " = CURR.sortvalue " _
& " AND PREV.orderno < CURR.orderno ) " _
& " ORDER BY PREV." & strOrderBy & " DESC, PREV.orderno DESC "
sSQLGetNextOrder = "SELECT top(1) NXT.* " _
& " FROM [Order] NXT " _
& " JOIN ( " _
& " SELECT " & strOrderBy & " sortvalue, orderno " _
& " FROM Order WHERE orderno='" & strCurrentOrder & "' " _
& " ) CURR " _
& " ON NXT." & strOrderBy & " > CURR.sortvalue " _
& " OR ( NXT." & strOrderBy & " = CURR.sortvalue " _
& " AND NXT.orderno > CURR.orderno ) " _
& " ORDER BY NXT." & strOrderBy & " ASC, NXT.orderno ASC "
(Apologies if this code has syntax errors, I have not been able to test it)
If orderno is always a number, you could omit the quote marks around strCurrentOrder.

My form freeze when exporting to XML

is this normal? I can't click anything in my form when I'm exporting a data to XML from 14k records? And I think my form freeze. I'm using vb.net in exporting file from database. Hope to hear positive response.
CODE :
Using xmlWriter As XmlWriter = xmlWriter.Create(oFileName, xmlSetting)
xmlWriter.WriteStartDocument()
xmlWriter.WriteStartElement("Products")
xmlWriter.WriteAttributeString("type", "array")
oDotNet.SqlDb.strCommand = "SELECT IsNULL(SuppCatNum, '') [Stock No], " & _
" ItemCode, " & _
" IsNULL(CodeBars, '') [BardCode List], " & _
" IsNULL(FrgnName, '') [FrgnName], " & _
" ItemName, " & _
" IsNULL(InvntryUom, '') [InvntryUom], " & _
" b.ItmsGrpCod [Category Code], " & _
" b.ItmsGrpNam [Category Name], " & _
" a.QryGroup1 [Allow Decimal], " & _
" Vat.Rate, " & _
" a.ManSerNum, " & _
" IsNULL(a.CardCode, '-1') [CardCode]" & _
" FROM OITM a" & _
" INNER JOIN OITB b ON a.ItmsGrpCod = b.ItmsGrpCod " & _
" INNER JOIN OVTG Vat ON a.VatGourpSa = Vat.Code " '& _
'" WHERE ItemCode = 'Davies EL-0020 White'"
ts_Progress.Maximum = oDotNet.SqlDb.Ds.Tables(0).DefaultView.Count
For i As Integer = 0 To oDotNet.SqlDb.Ds.Tables(0).DefaultView.Count - 1
xmlWriter.WriteStartElement("Product")
xmlWriter.WriteElementString("id", -1)
xmlWriter.WriteElementString("stock_no", oDotNet.SqlDb.GetField(i, "Stock No"))
xmlWriter.WriteElementString("reference", oDotNet.SqlDb.GetField(i, "ItemCode"))
xmlWriter.WriteElementString("name", oDotNet.SqlDb.GetField(i, "ItemName"))
xmlWriter.WriteElementString("short_name", oDotNet.SqlDb.GetField(i, "FrgnName"))
xmlWriter.WriteElementString("supplier_code", oDotNet.SqlDb.GetField(i, "CardCode"))
'*BardCode*'
Select Case oType
Case 1
Dim _BardCode As String = Nothing
oSql.strCommand = "SELECT BcdCode FROM OBCD bcd INNER JOIN OUOM uom ON bcd.UomEntry = uom.UomEntry " & _
" WHERE ItemCode = '" & oDotNet.SqlDb.GetField(i, "ItemCode") & "' AND bcd.BcdCode != '" & oDotNet.SqlDb.GetField(i, "BardCode List") & "' " & _
" /*AND uom.UomCode = '" & oDotNet.SqlDb.GetField(i, "InvntryUom") & "'*/ "
If oSql.Ds.Tables(0).DefaultView.Count > 0 Then
For oBardCode As Integer = 0 To oSql.Ds.Tables(0).DefaultView.Count - 1
_BardCode &= oSql.GetField(oBardCode).ToString & ", "
Next
_BardCode = oDotNet.SqlDb.GetField(i, "BardCode List") & ", " & _BardCode.Substring(0, _BardCode.Length - 2)
Else
_BardCode = oDotNet.SqlDb.GetField(i, "BardCode List")
End If
xmlWriter.WriteElementString("barcode_list", _BardCode)
xmlWriter.WriteElementString("category_id", -1)
xmlWriter.WriteElementString("unit_name", oDotNet.SqlDb.GetField(i, "InvntryUom")) 'oDotNet.SqlDb.GetField(i, "InvntryUom"))
xmlWriter.WriteElementString("retail_price", "")
'*WhsCode Here*'
Dim _WhsCode As String = Nothing
oSql.strCommand = "SELECT WhsCode FROM OITW WHERE ItemCode = '" & oDotNet.SqlDb.GetField(i, "ItemCode") & "' "
For oWhsCode As Integer = 0 To oSql.Ds.Tables(0).DefaultView.Count - 1
_WhsCode &= oSql.GetField(oWhsCode).ToString & ", "
Next
_WhsCode = _WhsCode.Substring(0, _WhsCode.Length - 2)
End Select
xmlWriter.WriteEndElement()
ts_Value += 1
ts_Progress.Value = ts_Value
Next
xmlWriter.WriteEndElement()
xmlWriter.WriteEndDocument()
End Using
You could try Application.DoEvents this is a very sloppy but easy fix to your problem. It will allow you to use the form still, but it will be very slow.

Using arrays for updates in visual basic

this is my existing code:
DBConn.BeginTrans
strSQL = "DELETE tblAvailable WHERE "
strSQL = strSQL + "(intResortID = " + Session("TypeID") + ")"
strSQL = strSQL + " AND (dtm BETWEEN CONVERT(DATETIME,'" + cstr(Year(dtmStart)) + "-" + cstr(Month(dtmStart)) + "-" + cstr(Day(dtmStart)) + "', 102)"
strSQL = strSQL + " AND CONVERT(DATETIME,'" + cstr(Year(dtmEnd)) + "-" + cstr(Month(dtmEnd)) + "-" + cstr(Day(dtmEnd)) + "', 102))"
'SY SINGH
'Add code to only delete out room types contained in the spreadsheet
Dim i
strSQL = strSQL & "AND (strRoomType='" & strRooms(0) & "'"
For i = 1 to m_Rooms
strSQL = strSQL & " OR strRoomType='" & strRooms(i) & "'"
next
strSQL = strSQL & ")"
I want to change it to do an update instead, setting curprice where strRoomType is equal to the array of rooms.
this is what I have come up with so far
strSQL = "Update tblAvailable set curprice ="+ FixNumber(curprice (intCurrentData))
response.Write(strSQL)
strSQL = strSQL +"WHERE intResortID = " + Session("TypeID")
response.Write(strSQL)
strSQL = strSQL + " AND dtm BETWEEN CONVERT(DATETIME,'" + cstr(Year(dtmStart)) + "-" + cstr(Month(dtmStart)) + "-" + cstr(Day(dtmStart)) + "', 102)"
response.Write(strSQL)
strSQL = strSQL + " AND CONVERT(DATETIME,'" + cstr(Year(dtmEnd)) + "-" + cstr(Month(dtmEnd)) + "-" + cstr(Day(dtmEnd)) + "', 102)"
response.Write(strSQL)
dim i
strSQL = strSQL + " AND (strRoomType='" & strRooms(0) & "'"
response.Write(strSQL)
For i = 1 to m_Rooms
strSQL = strSQL & " OR strRoomType='" & strRooms(i) & "'"
response.Write(strSQL)
next
strSQL = strSQL & ")"
response.Write(strSQL)
DBConn.Execute strSQL
this is the error I am receiving:
dtm'dtm' OR strRoomType='obeqvb'dtm' OR strRoomType='obeqvb')
Microsoft OLE DB Provider for SQL Server error '80040e14'
Incorrect syntax near 'obeqvb'.
/upload_excel_v3.asp, line 230
obeqvb is my strroomtype and dtm is my date
You should escape any single-quotes in your values by doubling them up
'my'roomtype should be 'my''roomtype'
And you're better off using where strRoomType in(...) instead of "or"

Resources