I have this code
Dim LogData As sterm.markdata = New sterm.markdata()
Dim datelistquery As String
Dim properdate As String
If Session("TenHolStDateHP1") = "%" or Session("TenHolStDateHP1") = "" Then
If Session("passedPropId") = "" Then
'QUERY USED IF NO DATE SELECTED AND A PROPID HAS NOT BEEN PASSED
datelistquery = "SELECT DISTINCT property_id, ' - Sleeps ' + cast(number_slept as varchar) as combsleeps, number_slept FROM openquery ("+Application("hpbDsrc")+",'SELECT property_id, number_slept FROM web_details WHERE location = ''"&Session("TenChosenLocCode")&"'' AND pets_yn like ''"&Session("TenPets")&"'' AND number_slept >= ''"&Session("TenAdults")&"'' AND on_hold = ''NO'' AND booked = ''NO'' ') ORDER BY number_slept, property_id"
Else
'QUERY USED IF NO DATE SELECTED AND A PROPID HAS BEEN PASSED
datelistquery = "SELECT DISTINCT property_id, ' - Sleeps ' + cast(number_slept as varchar) as combsleeps, number_slept FROM openquery ("+Application("hpbDsrc")+",'SELECT property_id, number_slept FROM web_details WHERE location = ''"&Session("TenChosenLocCode")&"'' AND property_id = ''"&Session("passedPropId")&"'' AND pets_yn like ''"&Session("TenPets")&"'' AND number_slept >= ''"&Session("TenAdults")&"'' AND on_hold = ''NO'' AND booked = ''NO'' ') ORDER BY number_slept, property_id"
End If
Else
If Session("holidayduration") = "7" Then
If Session("passedPropId") = "" Then
'QUERY USED IF DATE SELECTED AND 7 NIGHTS AND A PROPID HAS NOT BEEN PASSED
datelistquery = "SELECT DISTINCT property_id, ' - Sleeps ' + cast(number_slept as varchar) as combsleeps, number_slept FROM openquery ("+Application("hpbDsrc")+",'SELECT property_id, number_slept FROM web_details WHERE part_full_flag = ''F'' AND location = ''"&Session("TenChosenLocCode")&"'' AND pets_yn like ''"&Session("TenPets")&"'' AND number_slept >= ''"&Session("TenAdults")&"'' AND year_week = ''"&Session("TenHolStDateHP1")&"'' AND on_hold = ''NO'' AND booked = ''NO'' ') ORDER BY number_slept, property_id"
Else
'QUERY USED IF DATE SELECTED AND 7 NIGHTS AND A PROPID HAS BEEN PASSED
datelistquery = "SELECT DISTINCT property_id, ' - Sleeps ' + cast(number_slept as varchar) as combsleeps, number_slept FROM openquery ("+Application("hpbDsrc")+",'SELECT property_id, number_slept FROM web_details WHERE part_full_flag = ''F'' AND location = ''"&Session("TenChosenLocCode")&"'' AND property_id = ''"&Session("passedPropId")&"'' AND pets_yn like ''"&Session("TenPets")&"'' AND number_slept >= ''"&Session("TenAdults")&"'' AND year_week = ''"&Session("TenHolStDateHP1")&"'' AND on_hold = ''NO'' AND booked = ''NO'' ') ORDER BY number_slept, property_id"
End If
Else If Session("holidayduration") = "14" Then
theyear = Left(Session("TenHolStDateHP1"), 4)
theweek = Right(Session("TenHolStDateHP1"), 2)
If theweek < "52" then
theyear = theyear
If theweek < "10" then
theweek = "0" & theweek + 1
Else
theweek = theweek + 1
End If
Else
If (theyear = "2015" and theweek < "53") or (theyear = "2020" and theweek < "53") or (theyear = "2026" and theweek < "53") or (theyear = "2032" and theweek < "53") or (theyear = "2037" and theweek < "53") then
theyear = theyear
theweek = "53"
Else
theyear = theyear + 1
theweek = "01"
End If
End If
If Session("passedPropId") = "" Then
'QUERY USED IF DATE SELECTED AND 14 NIGHTS AND A PROPID HAS NOT BEEN PASSED
datelistquery = "SELECT DISTINCT property_id, ' - Sleeps ' + cast(number_slept as varchar) as combsleeps, number_slept FROM openquery ("+Application("hpbDsrc")+",'SELECT property_id, number_slept FROM web_details WHERE part_full_flag = ''F'' AND location = ''"&Session("TenChosenLocCode")&"'' AND pets_yn like ''"&Session("TenPets")&"'' AND number_slept >= ''"&Session("TenAdults")&"'' AND year_week in (''"&Session("TenHolStDateHP1")&"'',''"& theyear & theweek &"'') AND on_hold = ''NO'' AND booked = ''NO'' GROUP BY property_id HAVING count(property_id) > 1 ') ORDER BY number_slept, property_id"
Else
'QUERY USED IF DATE SELECTED AND 14 NIGHTS AND A PROPID HAS BEEN PASSED
datelistquery = "SELECT DISTINCT property_id, ' - Sleeps ' + cast(number_slept as varchar) as combsleeps, number_slept FROM openquery ("+Application("hpbDsrc")+",'SELECT property_id, number_slept FROM web_details WHERE part_full_flag = ''F'' AND location = ''"&Session("TenChosenLocCode")&"'' AND property_id = ''"&Session("passedPropId")&"'' AND pets_yn like ''"&Session("TenPets")&"'' AND number_slept >= ''"&Session("TenAdults")&"'' AND year_week in (''"&Session("TenHolStDateHP1")&"'',''"& theyear & theweek &"'') AND on_hold = ''NO'' AND booked = ''NO'' GROUP BY property_id HAVING count(property_id) > 1 ') ORDER BY number_slept, property_id"
End If
Else If Session("holidayduration") = "3/4" Then
If Session("passedPropId") = "" Then
'QUERY USED IF DATE SELECTED AND 3/4 NIGHTS AND A PROPID HAS NOT BEEN PASSED
datelistquery = "SELECT DISTINCT property_id, ' - Sleeps ' + cast(number_slept as varchar) as combsleeps, number_slept FROM openquery ("+Application("hpbDsrc")+",'SELECT property_id, number_slept FROM web_details WHERE (part_full_flag = ''P'' or split_weeks = ''Y'') AND location = ''"&Session("TenChosenLocCode")&"'' AND pets_yn like ''"&Session("TenPets")&"'' AND number_slept >= ''"&Session("TenAdults")&"'' AND year_week = ''"&Session("TenHolStDateHP1")&"'' AND on_hold = ''NO'' AND booked = ''NO'' ') ORDER BY number_slept, property_id"
Else
'QUERY USED IF DATE SELECTED AND 3/4 NIGHTS AND A PROPID HAS BEEN PASSED
datelistquery = "SELECT DISTINCT property_id, ' - Sleeps ' + cast(number_slept as varchar) as combsleeps, number_slept FROM openquery ("+Application("hpbDsrc")+",'SELECT property_id, number_slept FROM web_details WHERE (part_full_flag = ''P'' or split_weeks = ''Y'') AND location = ''"&Session("TenChosenLocCode")&"'' AND property_id = ''"&Session("passedPropId")&"'' AND pets_yn like ''"&Session("TenPets")&"'' AND number_slept >= ''"&Session("TenAdults")&"'' AND year_week = ''"&Session("TenHolStDateHP1")&"'' AND on_hold = ''NO'' AND booked = ''NO'' ') ORDER BY number_slept, property_id"
End If
End If
'Query to get date in nice format
properdate = "SELECT * FROM openquery ("+Application("hpbDsrc")+", 'SELECT starting_period from web_header WHERE year_week = ''"&Session("TenHolStDateHP1")&"'' ')"
Dim drCode7 As DataSet = LogData.StermQ3(properdate)
dgAvailable2.DataSource = drCode7.Tables(0).DefaultView
dgAvailable2.DataBind()
End If
dd1.DataSource = LogData.StermQ3(datelistquery).Tables(0).DefaultView
dd1.DataBind()
dd1.Items.Insert(0, new listitem("Any location", "%"))
And the error CommandText has not been initialized keeps showing up on the IIS event viewer log
I can't replicate the problem myself but I know it is happening can anyone suggest anything
The error says it happens with this line dd1.DataSource = LogData.StermQ3(datelistquery).Tables(0).DefaultView
Thanks
Jamie
I think you are in a situation where none of the following conditions are met:
Session("TenHolStDateHP1") = "%"
Session("TenHolStDateHP1") = ""
Session("holidayduration") = "3/4"
Session("holidayduration") = "14"
Session("holidayduration") = "7"
Since you don't initialize datelistquery to anything and you end in an else if it seems possible that you are not assigning a query to this string and could pass an empty string to your StermQ3 function.
You may want to add an else statement to the end of your chain of if/else if statements as a catchall. What you would set datelistquery to in the else statement depends on what you are doing.
Related
ALTER PROCEDURE [dbo].[getmytrasactions]
#pageindex int,
#pagesize int,
#whereclause varchar(1024),
#orderby varchar(1024),
#direction varchar(1024),
#starttimestampdate datetime,
#endtimestampdate datetime,
#applicationid int,
#ignoretimestamps bit = 0
AS
SET NOCOUNT ON
declare #rowstart int, #rowend int
declare #orderclause varchar(100)
declare #starttimestampdateid int
declare #endtimestampdateid int
if isnull(#pagesize,0) < 1
set #pagesize = 50
if isnull(#pageindex,0) < 1
set #pageindex = 1
set #rowstart = ((#pageindex -1) * #pagesize) + 1
set #rowend = #rowstart + #pagesize -1
create table #temp (rank int identity, id bigint, timestampdateid int, applicationid int)
if #orderby = 'rquid' or #orderby = 'policyguid'
set #orderclause = 'ORDER BY Convert(varchar(36), ' + #orderby + ') ' + #direction
else
set #orderclause = 'ORDER BY ' + #orderby + ' ' + #direction
print #orderclause
if #starttimestampdate is null
set #starttimestampdate = getdate()
if #endtimestampdate is null
set #endtimestampdate = #starttimestampdate
if #applicationid is null
set #applicationid = 0
set #starttimestampdateid = (datepart(yyyy, #starttimestampdate) * 10000) + (datepart(mm, #starttimestampdate) * 100) + (datepart(dd, #starttimestampdate))
set #endtimestampdateid = (datepart(yyyy, #endtimestampdate) * 10000) + (datepart(mm, #endtimestampdate) * 100) + (datepart(dd, #endtimestampdate))
if isnull(#whereclause, '') = ''
set #whereclause = 'where 1=1'
set #whereclause = #whereclause + ' and applicationid = ' + cast(#applicationid as varchar(2))
-- Add the timestamp to the whereclause to make the search more efficient. in some cases
-- we will want to ignore the timestamps. For example, when passing in a policyguid.
if #ignoretimestamps = 0
set #whereclause = #whereclause + ' and timestampdateid between ' + cast(#starttimestampdateid as char(8)) + ' and ' + cast(#endtimestampdateid as char(8))
exec ('insert #temp (id,timestampdateid,applicationid)
SELECT id,timestampdateid,applicationid
FROM dbo.getmytimes with (nolock)' + ' ' + #whereclause + ' ' + #orderclause)
select ##rowcount
SELECT tt.Id
, [Timestamp]
, tt.ApplicationId
, RqUID
, ContextGUID
, tt.PolicyGUID
, TransactionName
, TransactionDesc
, TransactionTime/1000. as TransactionTime
, ComputerName
, TransactionType
, ActivityType
, UserTypeId
, case when StatusCode = 0 then 'green'
when StatusCode = 100 then 'red'
when StatusCode > 0 and StatusCode < 100 then 'yellow'
else null end as StatusCode
, ErrorNumber
, Details
, BuildLabel
, [Level]
FROM getmytimes tt with (nolock)
join #temp t on t.id = tt.Id and t.timestampdateid = tt.TimeStampDateID and t.applicationid = tt.ApplicationID
WHERE t.rank between + #rowstart and #rowend
AND ((#ignoretimestamps=0 AND tt.timestampdateid between #starttimestampdateid and #endtimestampdateid) OR #ignoretimestamps=1)
AND tt.ApplicationID = #ApplicationID
ORDER BY t.Rank
I am trying to convert this to a stored procedure in SQL Server from an ASP script. I have tried to follow the procedures outlined at http://www.sommarskog.se/dyn-search.html, but due to lack of understanding; I can't figure out what is needed to create the search string. Once I can figure that out, then I can attach the string to the rest of the dynamic sql. I have the list to table function, and the intList_tabletype defined in the database, as well as the rest of the SP. The searchArr variable can be one keyword, a delimited list of keywords or a phrase. Any help will be greatly appreciated. Thanks
'SQL - Keywords
If Len(strSearch) > 0 Then
'Create array of keywords. If we're doing a PHRase
'search, an array with only one position is created
'containing the entire search string. If an AND or
'an OR "keyword" search is being performed, each word
'is put into it's own array position.
If strSearchType = "PHR" Then
searchArr(0) = Trim(strSearch)
Else
searchArr = strSearch.Split(" "c)
End If
'Keyword search SQL
tmpSQL1 = "(Brewery.BreweryName LIKE "
tmpSQL2 = "(Products.description LIKE "
tmpSQL3 = "(Products.Notes LIKE "
tmpSQL4 = "(Products.SKU LIKE "
For i = 0 To UBound(searchArr)
If i = UBound(searchArr) Then
tmpSQL1 = tmpSQL1 & "'%" & searchArr(i) & "%')"
tmpSQL2 = tmpSQL2 & "'%" & searchArr(i) & "%')"
tmpSQL3 = tmpSQL3 & "'%" & searchArr(i) & "%')"
tmpSQL4 = tmpSQL4 & "'%" & searchArr(i) & "%')"
Else
tmpSQL1 = tmpSQL1 & "'%" & searchArr(i) & "%' " & strSearchType & " Brewery.BreweryName LIKE "
tmpSQL2 = tmpSQL2 & "'%" & searchArr(i) & "%' " & strSearchType & " Products.description LIKE "
tmpSQL3 = tmpSQL3 & "'%" & searchArr(i) & "%' " & strSearchType & " Products.Notes LIKE "
tmpSQL4 = tmpSQL4 & "'%" & searchArr(i) & "%' " & strSearchType & " Products.SKU LIKE "
End If
Next
'Put it all together
searchSQL = searchSQL & "AND (" & tmpSQL1 & " OR " & tmpSQL2 & " OR " & tmpSQL3 & " OR " & tmpSQL4 & ") "
End If
When i run this script on the web page, I get this string.
Single keyword Or Phrase
AND ((Brewery.BreweryName LIKE '%Bud%') OR (Products.description LIKE '%Bud%') OR (Products.Notes LIKE '%Bud%') OR (Products.SKU LIKE '%Bud%') OR (Brands.Brand LIKE '%Bud%'))
Multiple Keywords
AND ((Brewery.BreweryName LIKE '%Bud%' OR Brewery.BreweryName LIKE '%Busch%') OR (Products.description LIKE '%Bud%' OR Products.description LIKE '%Busch%') OR (Products.Notes LIKE '%Bud%' OR Products.Notes LIKE '%Busch%') OR (Products.SKU LIKE '%Bud%' OR Products.SKU LIKE '%Busch%') OR (Brands.Brand LIKE '%Bud%' OR Brands.Brand LIKE '%Busch%'))
This is the Procedure I have come up so far.
ALTER PROCEDURE [dbo].[GetProductsBySearch]
#idProduct int = NULL,
#sku nvarchar(20) = NULL,
#breweryname nvarchar(40) = NULL,
#brand nvarchar(40) = NULL,
#country nvarchar(15) = NULL,
#prodname nvarchar(40) = NULL,
#searchStr nvarchar(MAX) = NULL,
--#PHRtbl intlist_tbltype READONLY,
#sortExpression nvarchar(50) = NULL,
#startRowIndex int,
#maximumRows int,
#idLocation int = NULL,
#idBrand int = NULL,
#strSearchType nvarchar(5) = ' OR ',
#debug bit = 0
AS
DECLARE #sql nvarchar(MAX),
#paramlist nvarchar(4000),
#nl char(2) = char(13) + char(10)
DECLARE #PHRtbl TABLE
( PK INT IDENTITY(1,1) PRIMARY KEY,
item NVARCHAR (MAX)
)
IF #sortExpression IS NULL
SET #sortExpression = 'sku'
INSERT INTO #PHRtbl
SELECT item FROM [dbo].[udf_List2Table](#searchStr,',')
DECLARE #i INT
SELECT #i = MIN(PK) FROM #PHRtbl
DECLARE #max INT
SELECT #max = MAX(PK) FROM #PHRtbl
DECLARE #SearchSQL AS NVARCHAR(MAX) = ''
DECLARE #item AS NVARCHAR(MAX) = NULL
DECLARE #tmpSQL1 AS NVARCHAR(MAX) = '(Brewery.BreweryName LIKE '
DECLARE #tmpSQL2 AS NVARCHAR(MAX) = '(Products.description LIKE '
DECLARE #tmpSQL3 AS NVARCHAR(MAX) = '(Products.Notes LIKE '
DECLARE #tmpSQL4 AS NVARCHAR(MAX) = '(Products.SKU LIKE '
DECLARE #tmpSQL5 AS NVARCHAR(MAX) = '(Brands.Brand LIKE '
SELECT #sql =
'SELECT SKU, productName, imgUrlThumb, Size, ProdType, CanType,
CanManufacturer, breweryName, locName, CountryFlag, Brand
FROM
(SELECT Products.SKU, Products.Description as productName, Products.imgUrlThumb, LookupSize.Size, ProdType.ProdType, CanTypes.Description AS CanType,
CanManufacturer.CanManufacturer, brewery.breweryName, Locations.locName, Locations.CountryFlag, Brands.Brand,
ROW_NUMBER() OVER(ORDER BY ' + #sortExpression + ') AS RowNum
FROM Products INNER JOIN
brewery ON Products.idBrewery = brewery.idBrewery INNER JOIN
CanManufacturer ON Products.idCanManufacturer = CanManufacturer.idCanManufacturer INNER JOIN
CanTypes ON Products.idCanType = CanTypes.idCanType INNER JOIN
Locations ON brewery.idLocation = Locations.idLocation INNER JOIN
LookupSize ON Products.idSize = LookupSize.idSize INNER JOIN
ProdType ON Products.idProdType = ProdType.idProdtype INNER JOIN
CatProd ON Products.idProduct = CatProd.idProduct INNER JOIN
Categories ON CatProd.idCategory = Categories.idCategory INNER JOIN
Brands ON Brands.idBrand = Products.idBrand
WHERE 1 = 1 ' + #nl
IF #searchStr IS NOT NULL
WHILE #i <= #max
BEGIN
SELECT #item = item FROM #PHRtbl WHERE PK = #i
IF (#i = #max)
BEGIN
SET #tmpSQL1 += ''%'' & #item + ''%')'
SET #tmpSQL2 += ''%'' & #item + ''%')'
SET #tmpSQL3 += ''%'' & #item + ''%')'
SET #tmpSQL4 += ''%'' & #item + ''%')'
SET #tmpSQL5 += ''%'' & #item + ''%')'
END
ELSE
BEGIN
SET #tmpSQL1 += ''%'' & #item + ''%')' + #strSearchType + ' Brewery.BreweryName LIKE '
SET #tmpSQL2 += ''%'' & #item + ''%')' + #strSearchType + ' Products.description LIKE '
SET #tmpSQL3 += ''%'' & #item + ''%')' + #strSearchType + ' Products.Notes LIKE '
SET #tmpSQL4 += ''%'' & #item + ''%')' + #strSearchType + ' Products.SKU LIKE '
SET #tmpSQL5 += ''%'' & #item + ''%')' + #strSearchType + ' Brands.Brand LIKE '
END
SELECT #item = NULL
SET #i = #i + 1
END
--moved this out of the while loop
-- put it all together
SET #SearchSQL = #SearchSQL + 'AND (' + #tmpSQL1 + ' OR ' + #tmpSQL2 + ' OR ' + #tmpSQL3 + ' OR ' + #tmpSQL4 + ' OR ' + #tmpSQL5 + ') ' + #nl
-- Uncommend below to check the SQL
PRINT #SearchSQL
SELECT #sql += ' #SearchSQL' + #nl
IF #idProduct IS NOT NULL
SELECT #sql += ' AND Products.idProduct = #idProduct' + #nl
IF #idBrand IS NOT NULL
SELECT #sql += ' AND Products.idBrand = #idBrand' + #nl
IF #idLocation IS NOT NULL
SELECT #sql += ' AND Brewery.idLocation = #idLocation' + #nl
IF #brand IS NOT NULL
SELECT #sql += ' AND Brands.brand LIKE ''%'' + #brand + ''%''' + #nl
IF #breweryname IS NOT NULL
SELECT #sql += ' AND Brewery.breweryName LIKE ''%'' + #breweryname + ''%''' + #nl
IF #prodname IS NOT NULL
SELECT #sql += ' AND Products.Description LIKE ''%'' + #prodname + ''%''' + #nl
IF #searchStr IS NOT NULL
SELECT #sql += ' #searchStr' + #nl
SELECT #sql += ') AS myData
WHERE RowNum BETWEEN (' + CONVERT(nvarchar(10), #startRowIndex) +
' - 1) * ' + CONVERT(nvarchar(10),#MaximumRows) + ' AND (((' + CONVERT(nvarchar(10), #startRowIndex) + ' - 1) * '
+ CONVERT(nvarchar(10), #maximumRows) + ' + 1) + ' + CONVERT(nvarchar(10), #maximumRows) + ') - 1'
--IF EXISTS (SELECT * FROM #PHRtbl)
-- SELECT #sql += ' AND o.EmployeeID IN (SELECT val FROM #employeetbl)' + #nl
--SELECT #sql += ' ORDER BY o.OrderID' + #nl
IF #debug = 1
PRINT #sql
SELECT #paramlist = '#idProduct int,
#sku nvarchar(20) ,
#breweryname nvarchar(40) ,
#brand nvarchar(40) ,
#country nvarchar(15) ,
#prodname nvarchar(40) ,
#searchStr nvarchar(MAX) ,
#PHRtbl intlist_tbltype READONLY,
#sortExpression nvarchar(50),
#startRowIndex int,
#maximumRows int,
#idLocation int,
#idBrand int,
#strSearchType nvarchar(5)'
EXEC sp_executesql #sql, #paramlist,
#idProduct,#sku,#breweryname,#brand,#country,#prodname,#searchStr,#PHRtbl,#sortExpression,
#startRowIndex,#maximumRows,#idLocation,#idBrand
Now when I try to execute the procedure I am getting the following errors. Due to the While loop to build the string. Know I have to figure out what is causing the error, and build the string and attach it #SQL that is being built.
**Msg 402, Level 16, State 1, Procedure GetProductsBySearch, Line 75
The data types varchar and varchar are incompatible in the modulo operator.
**
I was able to get the procedure to compile in the database by changing the quotes in this part.
IF (#i = #max)
BEGIN
SET #tmpSQL1 += '''%' + #item + '%'')'
SET #tmpSQL2 += '''%' + #item + '%'')'
SET #tmpSQL3 += '''%' + #item + '%'')'
SET #tmpSQL4 += '''%' + #item + '%'')'
SET #tmpSQL5 += '''%' + #item + '%'')'
END
ELSE
BEGIN
SET #tmpSQL1 += '''%' + #item + '%'')' + #strSearchType + ' Brewery.BreweryName LIKE '
SET #tmpSQL2 += '''%' + #item + '%'')' + #strSearchType + ' Products.description LIKE '
SET #tmpSQL3 += '''%' + #item + '%'')' + #strSearchType + ' Products.Notes LIKE '
SET #tmpSQL4 += '''%' + #item + '%'')' + #strSearchType + ' Products.SKU LIKE '
SET #tmpSQL5 += '''%' + #item + '%'')' + #strSearchType + ' Brands.Brand LIKE '
END
Now when I execute it I get this error.
Msg 206, Level 16, State 2, Line 0
Operand type clash: table is incompatible with nvarchar
I suspect the above section is the culprit. I have a Print Statement to Print the Strings as they are built, the error comes up first. Where or how do I see what the #SearchStr variable looks like?
I have extracted that section of code into a new window. With one value in the searchStr variable I get the the correct build of the searchSQL.
AND ((Brewery.BreweryName LIKE '%Bud%')
OR (Products.description LIKE '%Bud%')
OR (Products.Notes LIKE '%Bud%')
OR (Products.SKU LIKE '%Bud%')
OR (Brands.Brand LIKE '%Bud%')
)
However when I add another item to the list I get this:
AND ((Brewery.BreweryName LIKE '%Bud%') OR Brewery.BreweryName LIKE
OR (Products.description LIKE '%Bud%') OR Products.description LIKE
OR (Products.Notes LIKE '%Bud%') OR Products.Notes LIKE
OR (Products.SKU LIKE '%Bud%') OR Products.SKU LIKE
OR (Brands.Brand LIKE '%Bud%') OR Brands.Brand LIKE
)
I am almost there. Just need to figure what part of the string needs readjusting to get it right
AND ((Brewery.BreweryName LIKE '%Bud%') OR Brewery.BreweryName LIKE
'%Busch%')
OR (Products.description LIKE '%Bud%') OR Products.description LIKE
'%Busch%')
OR (Products.Notes LIKE '%Bud%') OR Products.Notes LIKE
'%Busch%')
OR (Products.SKU LIKE '%Bud%') OR Products.SKU LIKE
'%Busch%')
OR (Brands.Brand LIKE '%Bud%') OR Brands.Brand LIKE
'%Busch%')
)
It suppose there is chart to be appeared. But, it doesnt as there is problem regarding dbnull issue. This happen when either one of three select statement has no data.
Dim user As String = Session("NoMatrik")
Dim resultId As Object = Session("max")
Dim idQuery = "select max(resultid) as id from tblResult where result_nomatric = #matric and result_quiz_id = 1 UNION All " +
"select max(resultid) as id from tblResult where result_nomatric = #matric and result_quiz_id = 2 UNION All " +
"select max(resultid) as id from tblResult where result_nomatric = #matric and result_quiz_id = 3"
conn.Open()
Dim cmdGetId As New SqlCommand(idQuery, conn)
cmdGetId.Parameters.AddWithValue("#matric", user)
Dim maxIDs As SqlDataReader = cmdGetId.ExecuteReader
Dim IDs As String = ""
While maxIDs.Read
IDs += maxIDs("id").ToString() + ", "
End While
maxIDs.Close()
IDs = IDs.Substring(0, IDs.Length - 2)
Dim cmdString = "Select tblResult.result_quiz_id as Quiz,count(TblAnswer.AnswerType) as answerCount , TblAnswer.AnswerType " +
"from TblResultDetail inner join TblAnswer on TblResultDetail.ResultDetail_Answer_Id = TblAnswer.AnswerId " +
"inner join tblResult on tblResult.resultid = TblResultDetail.ResultDetail_Result_Id " +
"where TblResultDetail.ResultDetail_Result_Id in (" + IDs + ") " +
"group by TblAnswer.AnswerType, tblResult.result_quiz_id order by TblAnswer.AnswerType"
Dim cmd As New SqlCommand(cmdString, conn)
If IsDBNull(resultId) Then
Label1.Visible = True
chrtResult.Visible = False
Else
Dim dr1 As SqlDataReader
dr1 = cmd.ExecuteReader
While dr1.Read()
Dim tempArr(0) As Double
Dim count As Double = dr1("answerCount")
tempArr(0) = count
Dim Type As String = dr1("AnswerType").ToString()
Dim level As Integer = dr1("Quiz")
chrtResult.Series(Type).Points(level - 1).YValues = tempArr
End While
End If
conn.Close()
End If
End Sub
an error, Incorrect syntax near '(' appear at line dr1 = cmd.ExecuteReader. So , how I want to fix this error?
Update your first query to exclude any Null values using a HAVING clause like so:
Dim idQuery = "select max(resultid) as id from tblResult " +
"where result_nomatric = #matric and result_quiz_id = 1 " +
"having max(resultid) is not null " +
"UNION All " +
"select max(resultid) as id from tblResult " +
"where result_nomatric = #matric and result_quiz_id = 2 " +
"having max(resultid) is not null " +
"UNION All " +
"select max(resultid) as id from tblResult " +
"where result_nomatric = #matric and result_quiz_id = 3 " +
"having max(resultid) is not null"
The having max(resultid) is not null will exclude any nulls in your UNION ALL.
If there are no IDs returned, you simply need to do a check on this before you execute your next block of code and do as #DmitriE suggests with the adding of quotes. Reorganise it to look like:
While maxIDs.Read
IDs += "'" + maxIDs("id").ToString() + "', "
End While
If IDs = "" Then
Label1.Visible = True
chrtResult.Visible = False
Else
IDs = IDs.Substring(0, IDs.Length - 2)
Dim cmdString = "Select ....."
Dim dr1 As SqlDataReader
dr1 = cmd.ExecuteReader
While dr1.Read()
' YOUR WHILE LOOP CODE HERE'
End While
End If
This should be
While maxIDs.Read
IDs += "'" + maxIDs("id").ToString() + "', "
End While
and then you need to remove last single quote.
in clause should follow this format: where x.id in ('id1', 'id2', 'idN')
I have few tables in database that are having huge amount of data. My need is
1 : To query data exist for more than one year.
2 : Export and archive them to some file.
3 : At any point of time I can insert those data back to database.
The data may or may not contain COMMA, so not sure if I should export them to csv format.
Which is the best file format I should go for ??
What should be the file size limitation here ??
This script exports rows from specified tables to INSERT statement for any tables structure. So, you'll just need to copy the result and run it in sql document of SSMS -
DECLARE
#TableName SYSNAME
, #ObjectID INT
, #IsImportIdentity BIT = 1
DECLARE [tables] CURSOR READ_ONLY FAST_FORWARD LOCAL FOR
SELECT
'[' + s.name + '].[' + t.name + ']'
, t.[object_id]
FROM (
SELECT DISTINCT
t.[schema_id]
, t.[object_id]
, t.name
FROM sys.objects t WITH (NOWAIT)
JOIN sys.partitions p WITH (NOWAIT) ON p.[object_id] = t.[object_id]
WHERE p.[rows] > 0
AND t.[type] = 'U'
) t
JOIN sys.schemas s WITH (NOWAIT) ON t.[schema_id] = s.[schema_id]
WHERE t.name IN ('<your table name>')
OPEN [tables]
FETCH NEXT FROM [tables] INTO
#TableName
, #ObjectID
DECLARE
#SQLInsert NVARCHAR(MAX)
, #SQLColumns NVARCHAR(MAX)
, #SQLTinyColumns NVARCHAR(MAX)
WHILE ##FETCH_STATUS = 0 BEGIN
SELECT
#SQLInsert = ''
, #SQLColumns = ''
, #SQLTinyColumns = ''
;WITH cols AS
(
SELECT
c.name
, datetype = t.name
, c.column_id
FROM sys.columns c WITH (NOWAIT)
JOIN sys.types t WITH (NOWAIT) ON c.system_type_id = t.system_type_id AND c.user_type_id = t.user_type_id
WHERE c.[object_id] = #ObjectID
AND (c.is_identity = 0 OR #IsImportIdentity = 1)
AND c.is_computed = 0
AND t.name NOT IN ('xml', 'geography', 'geometry', 'hierarchyid')
)
SELECT
#SQLInsert = 'INSERT INTO ' + #TableName + ' (' + STUFF((
SELECT ', [' + c.name + ']'
FROM cols c
ORDER BY c.column_id
FOR XML PATH, TYPE, ROOT).value('.', 'NVARCHAR(MAX)'), 1, 2, '') + ')'
, #SQLTinyColumns = STUFF((
SELECT ', ' + c.name
FROM cols c
ORDER BY c.column_id
FOR XML PATH, TYPE, ROOT).value('.', 'NVARCHAR(MAX)'), 1, 2, '')
, #SQLColumns = STUFF((SELECT CHAR(13) +
CASE
WHEN c.datetype = 'uniqueidentifier'
THEN ' + '', '' + ISNULL('''''''' + CAST([' + c.name + '] AS VARCHAR(MAX)) + '''''''', ''NULL'')'
WHEN c.datetype IN ('nvarchar', 'varchar', 'nchar', 'char', 'varbinary', 'binary')
THEN ' + '', '' + ISNULL('''''''' + CAST(REPLACE([' + c.name + '], '''''''', '''''''''''' ) AS NVARCHAR(MAX)) + '''''''', ''NULL'')'
WHEN c.datetype = 'datetime'
THEN ' + '', '' + ISNULL('''''''' + CONVERT(VARCHAR, [' + c.name + '], 120) + '''''''', ''NULL'')'
ELSE
' + '', '' + ISNULL(CAST([' + c.name + '] AS NVARCHAR(MAX)), ''NULL'')'
END
FROM cols c
ORDER BY c.column_id
FOR XML PATH, TYPE, ROOT).value('.', 'NVARCHAR(MAX)'), 1, 10, 'CHAR(13) + '', ('' +')
DECLARE #SQL NVARCHAR(MAX) = '
SET NOCOUNT ON;
DECLARE
#SQL NVARCHAR(MAX) = ''''
, #x INT = 1
, #count INT = (SELECT COUNT(1) FROM ' + #TableName + ')
IF EXISTS(
SELECT 1
FROM tempdb.dbo.sysobjects
WHERE ID = OBJECT_ID(''tempdb..#import'')
)
DROP TABLE #import;
SELECT ' + #SQLTinyColumns + ', ''RowNumber'' = ROW_NUMBER() OVER (ORDER BY ' + #SQLTinyColumns + ')
INTO #import
FROM ' + #TableName + '
WHILE #x < #count BEGIN
SELECT #SQL = ''VALUES '' + STUFF((
SELECT ' + #SQLColumns + ' + '')''' + '
FROM #import
WHERE RowNumber BETWEEN #x AND #x + 9
FOR XML PATH, TYPE, ROOT).value(''.'', ''NVARCHAR(MAX)''), 1, 2, CHAR(13) + '' '') + '';''
PRINT(''' + #SQLInsert + ''')
PRINT(#SQL)
SELECT #x = #x + 10
END'
EXEC sys.sp_executesql #SQL
FETCH NEXT FROM [tables] INTO
#TableName
, #ObjectID
END
CLOSE [tables]
DEALLOCATE [tables]
In output you get something like this (AdventureWorks.Person.Address):
INSERT INTO [Person].[Address] ([AddressID], [AddressLine1], [AddressLine2], [City], [StateProvinceID], [PostalCode], [rowguid], [ModifiedDate])
VALUES
(1, '1970 Napa Ct.', NULL, 'Bothell', 79, '98011', '9AADCB0D-36CF-483F-84D8-585C2D4EC6E9', '2002-01-04 00:00:00')
, (2, '9833 Mt. Dias Blv.', NULL, 'Bothell', 79, '98011', '32A54B9E-E034-4BFB-B573-A71CDE60D8C0', '2003-01-01 00:00:00')
, (3, '7484 Roundtree Drive', NULL, 'Bothell', 79, '98011', '4C506923-6D1B-452C-A07C-BAA6F5B142A4', '2007-04-08 00:00:00')
, (4, '9539 Glenside Dr', NULL, 'Bothell', 79, '98011', 'E5946C78-4BCC-477F-9FA1-CC09DE16A880', '2003-03-07 00:00:00')
, (5, '1226 Shoe St.', NULL, 'Bothell', 79, '98011', 'FBAFF937-4A97-4AF0-81FD-B849900E9BB0', '2003-01-20 00:00:00')
, (6, '1399 Firestone Drive', NULL, 'Bothell', 79, '98011', 'FEBF8191-9804-44C8-877A-33FDE94F0075', '2003-03-17 00:00:00')
, (7, '5672 Hale Dr.', NULL, 'Bothell', 79, '98011', '0175A174-6C34-4D41-B3C1-4419CD6A0446', '2004-01-12 00:00:00')
, (8, '6387 Scenic Avenue', NULL, 'Bothell', 79, '98011', '3715E813-4DCA-49E0-8F1C-31857D21F269', '2003-01-18 00:00:00')
, (9, '8713 Yosemite Ct.', NULL, 'Bothell', 79, '98011', '268AF621-76D7-4C78-9441-144FD139821A', '2006-07-01 00:00:00')
, (10, '250 Race Court', NULL, 'Bothell', 79, '98011', '0B6B739D-8EB6-4378-8D55-FE196AF34C04', '2003-01-03 00:00:00');
UPDATE:
And this script exports rows from specified tables to CSV format in output window for any tables structure.
DECLARE
#TableName SYSNAME
, #ObjectID INT
DECLARE [tables] CURSOR READ_ONLY FAST_FORWARD LOCAL FOR
SELECT
'[' + s.name + '].[' + t.name + ']'
, t.[object_id]
FROM (
SELECT DISTINCT
t.[schema_id]
, t.[object_id]
, t.name
FROM sys.objects t WITH (NOWAIT)
JOIN sys.partitions p WITH (NOWAIT) ON p.[object_id] = t.[object_id]
WHERE p.[rows] > 0
AND t.[type] = 'U'
) t
JOIN sys.schemas s WITH (NOWAIT) ON t.[schema_id] = s.[schema_id]
WHERE t.name IN ('<your table name>')
OPEN [tables]
FETCH NEXT FROM [tables] INTO
#TableName
, #ObjectID
DECLARE
#SQLInsert NVARCHAR(MAX)
, #SQLColumns NVARCHAR(MAX)
, #SQLTinyColumns NVARCHAR(MAX)
WHILE ##FETCH_STATUS = 0 BEGIN
SELECT
#SQLInsert = ''
, #SQLColumns = ''
, #SQLTinyColumns = ''
;WITH cols AS
(
SELECT
c.name
, datetype = t.name
, c.column_id
FROM sys.columns c WITH (NOWAIT)
JOIN sys.types t WITH (NOWAIT) ON c.system_type_id = t.system_type_id AND c.user_type_id = t.user_type_id
WHERE c.[object_id] = #ObjectID
AND c.is_computed = 0
AND t.name NOT IN ('xml', 'geography', 'geometry', 'hierarchyid')
)
SELECT
#SQLTinyColumns = STUFF((
SELECT ', [' + c.name + ']'
FROM cols c
ORDER BY c.column_id
FOR XML PATH, TYPE, ROOT).value('.', 'NVARCHAR(MAX)'), 1, 2, '')
, #SQLColumns = STUFF((SELECT CHAR(13) +
CASE
WHEN c.datetype = 'uniqueidentifier'
THEN ' + '';'' + ISNULL('''' + CAST([' + c.name + '] AS VARCHAR(MAX)) + '''', ''NULL'')'
WHEN c.datetype IN ('nvarchar', 'varchar', 'nchar', 'char', 'varbinary', 'binary')
THEN ' + '';'' + ISNULL('''' + CAST(REPLACE([' + c.name + '], '''', '''''''') AS NVARCHAR(MAX)) + '''', ''NULL'')'
WHEN c.datetype = 'datetime'
THEN ' + '';'' + ISNULL('''' + CONVERT(VARCHAR, [' + c.name + '], 120) + '''', ''NULL'')'
ELSE
' + '';'' + ISNULL(CAST([' + c.name + '] AS NVARCHAR(MAX)), ''NULL'')'
END
FROM cols c
ORDER BY c.column_id
FOR XML PATH, TYPE, ROOT).value('.', 'NVARCHAR(MAX)'), 1, 10, 'CHAR(13) + '''' +')
DECLARE #SQL NVARCHAR(MAX) = '
SET NOCOUNT ON;
DECLARE
#SQL NVARCHAR(MAX) = ''''
, #x INT = 1
, #count INT = (SELECT COUNT(1) FROM ' + #TableName + ')
IF EXISTS(
SELECT 1
FROM tempdb.dbo.sysobjects
WHERE ID = OBJECT_ID(''tempdb..#import'')
)
DROP TABLE #import;
SELECT ' + #SQLTinyColumns + ', ''RowNumber'' = ROW_NUMBER() OVER (ORDER BY ' + #SQLTinyColumns + ')
INTO #import
FROM ' + #TableName + '
WHILE #x < #count BEGIN
SELECT #SQL = STUFF((
SELECT ' + #SQLColumns + ' + ''''' + '
FROM #import
WHERE RowNumber BETWEEN #x AND #x + 9
FOR XML PATH, TYPE, ROOT).value(''.'', ''NVARCHAR(MAX)''), 1, 1, '''')
PRINT(#SQL)
SELECT #x = #x + 10
END'
EXEC sys.sp_executesql #SQL
FETCH NEXT FROM [tables] INTO
#TableName
, #ObjectID
END
CLOSE [tables]
DEALLOCATE [tables]
In output you get something like this (AdventureWorks.Person.Person):
1;EM;0;NULL;Ken;J;Sánchez;NULL;0;92C4279F-1207-48A3-8448-4636514EB7E2;2003-02-08 00:00:00
2;EM;0;NULL;Terri;Lee;Duffy;NULL;1;D8763459-8AA8-47CC-AFF7-C9079AF79033;2002-02-24 00:00:00
3;EM;0;NULL;Roberto;NULL;Tamburello;NULL;0;E1A2555E-0828-434B-A33B-6F38136A37DE;2001-12-05 00:00:00
4;EM;0;NULL;Rob;NULL;Walters;NULL;0;F2D7CE06-38B3-4357-805B-F4B6B71C01FF;2001-12-29 00:00:00
5;EM;0;Ms.;Gail;A;Erickson;NULL;0;F3A3F6B4-AE3B-430C-A754-9F2231BA6FEF;2002-01-30 00:00:00
6;EM;0;Mr.;Jossef;H;Goldberg;NULL;0;0DEA28FD-EFFE-482A-AFD3-B7E8F199D56F;2002-02-17 00:00:00
Try using the bcp command line utility, which is very efficient at handling import/export for large data sets:
bcp "select * from [YourTable]" queryout data.dat -n -S YourServer -d "YourDatabase" -T
-T means Trusted Authentication. -n means native format, so you don't need to worry about data types, commas, etc. However, this does mean you can't view the data in an editor; it's only available for loading back into SQL Server. You can use -c instead if you want CSV format.
To import back in:
bcp "[YourTable]" in data.dat -n -S YourServer -d "YourDatabase" -T
Updated Code
VB CODEBEHIND
Protected Sub cmdclick_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdclick.Click
Dim strConnString As String = WebConfigurationManager.ConnectionStrings("orca").ConnectionString
Dim con As New SqlConnection(strConnString)
Dim cmd As New SqlCommand("usp_validatecard", con)
cmd.CommandType = Data.CommandType.StoredProcedure
Dim GetTrack1 As String = ""
Dim GetTrack2 As String = ""
Dim SplitTrack As String = txtTrack.Text
If SplitTrack.Length.ToString = 19 Then
GetTrack1 = Mid(SplitTrack, 2, 6)
GetTrack2 = Mid(SplitTrack, 10, 9)
cmd.Parameters.Add("#track1", Data.SqlDbType.NVarChar).Value = GetTrack1
cmd.Parameters.Add("#track2", Data.SqlDbType.NVarChar).Value = GetTrack2
Try
con.Open()
Dim Result As Integer = cmd.ExecuteNonQuery()
Dim reader As SqlDataReader = cmd.ExecuteReader()
If reader.Read() Then
lblmemname.Text = Convert.ToString(reader(0))
lblmemnum.Text = Convert.ToString(reader(1))
lbltrack1.Text = Convert.ToString(reader(2))
lbltrack2.Text = Convert.ToString(reader(3))
lblmessage.Text = Convert.ToString(reader(4))
End If
Catch ex As SqlException
errmessage.Text = "Error"
Finally
con.Close()
End Try
ElseIf SplitTrack.Length.ToString = 8 Then
GetTrack1 = Mid(SplitTrack, 2, 6)
cmd.Parameters.Add("#track1", Data.SqlDbType.NVarChar).Value = GetTrack1
Try
con.Open()
Dim Result As Integer = cmd.ExecuteNonQuery()
Dim reader As SqlDataReader = cmd.ExecuteReader()
If reader.Read() Then
lblmemname.Text = Convert.ToString(reader(0))
lblmemnum.Text = Convert.ToString(reader(1))
lbltrack1.Text = Convert.ToString(reader(2))
lbltrack2.Text = Convert.ToString(reader(3))
lblmessage.Text = Convert.ToString(reader(4))
End If
Catch ex As SqlException
errmessage.Text = "Error"
Finally
con.Close()
End Try
ElseIf SplitTrack.Length.ToString = 11 Then
GetTrack2 = Mid(SplitTrack, 2, 9)
cmd.Parameters.Add("#track2", Data.SqlDbType.NVarChar).Value = GetTrack2
Try
con.Open()
Dim Result As Integer = cmd.ExecuteNonQuery()
Dim reader As SqlDataReader = cmd.ExecuteReader()
If reader.Read() Then
lblmemname.Text = Convert.ToString(reader(0))
lblmemnum.Text = Convert.ToString(reader(1))
lbltrack1.Text = Convert.ToString(reader(2))
lbltrack2.Text = Convert.ToString(reader(3))
lblmessage.Text = Convert.ToString(reader(4))
End If
Catch ex As SqlException
errmessage.Text = "Error"
Finally
con.Close()
End Try
Else
lblmessage.Text = "Could Not Find Any Tracks"
End If
MSSQL STORED PROCEDURE
ALTER Procedure [dbo].[usp_validatecard](
#memnum nvarchar(50) = '-',
#memname nvarchar(50) = '-',
#track1 nvarchar(50) = '-',
#track2 nvarchar(50) = '-',
#msgtrack1 nvarchar(50) = 'Track 1 is Blank',
#msgtrack2 nvarchar(50) = 'Track 2 is Blank',
#message nvarchar(100)= '-')
As
--select #cardid = '%128255? ;282556587?'
--select #track1 = '128255'
--select #track2 = '282556587'
-- track1 good, track2 good
If exists(select * from dbo.clubmembers where FAMILYID = #track1 and (CLUBCARD1 = #track2 or CLUBCARD2 = #track2))
begin
select #memname = lastname + ', ' + firstname, #memnum = MEMBERSHIPID from dbo.clubmembers where FAMILYID = #track1 and (CLUBCARD1 = #track2 or CLUBCARD2 = #track2)
if exists(select * from dbo.clubmembers where membershipid = #memnum and status = 'ACTIVE')
select #msgtrack1 = 'Track 1 is GOOD', #msgtrack2 = 'Track 2 is GOOD', #message = 'Card is GOOD'
else
select #msgtrack1 = 'Track 1 is GOOD but In-active', #msgtrack2 = 'Track 2 is GOOD but In-active', #message = 'Check Member Status in Membership'
end
-- track1 good and track2 bad
Else
If exists(select * from dbo.clubmembers where FAMILYID = #track1 and (CLUBCARD1 != #track2 and CLUBCARD2 != #track2))
begin
select #memname = lastname, #memnum = FAMILYID from dbo.clubmembers where FAMILYID = #track1 and (CLUBCARD1 != #track2 and CLUBCARD2 != #track2)
if exists(select * from dbo.clubmembers where FAMILYID = #track1 and (CLUBCARD1 != #track2 and CLUBCARD2 != #track2) and status = 'ACTIVE')
select #msgtrack1 = 'Track 1 is GOOD', #msgtrack2 = 'Track 2 is BAD', #message = 'Please re-encode card'
else
select #msgtrack1 = 'Track 1 is GOOD but In-Active', #msgtrack2 = 'Track 2 is BAD', #message = 'Please re-encode card and Check Member Status in Membership'
end
else
-- track1 bad, track2 good
If exists(select * from dbo.clubmembers where (CLUBCARD1 = #track2 or CLUBCARD2 = #track2) and FAMILYID != #track1)
begin
select #memname = lastname + ', ' + firstname, #memnum = MEMBERSHIPID from dbo.clubmembers where (CLUBCARD1 = #track2 or CLUBCARD2 = #track2)
If exists(select * from dbo.clubmembers where (CLUBCARD1 = #track2 or CLUBCARD2 = #track2) and FAMILYID != #track1 and STATUS = 'ACTIVE')
select #msgtrack1 = 'Track 1 is BAD', #msgtrack2 = 'Track 2 is GOOD', #message = 'Please re-encode card'
else
select #msgtrack1 = 'Track 1 is BAD', #msgtrack2 = 'Track 2 is GOOD but In-active', #message = 'Please re-encode card and Check member status in Membership'
end
select #memname, #memnum, #msgtrack1, #msgtrack2, #message
If you check if sp has two elements or not by doing
If sp.Length = 2 Then
...
End If
and inside the If block, you can do
Dim track1 as String = sp(0)
Dim track2 as String = sp(1)
C# is more to my liking but this is a rough cut of a method that will split your string, test for correct number of elements and then create database connection (assumed sql server but any ole db should work) and call your stored procedure.
Public Sub ProcessSwipe(ByVal value As String)
Dim splitValues() As String
Dim separator As Char = ";"
Dim connectionString As String = String.Empty
Dim storedProcName As String = String.Empty
' Edit these to sane values
connectionString = "Provider=SQLOLEDB;BData Source=localhost;Initial Catalog=msdb;Integrated Security=SSPI;"
storedProcName = "dbo.SaveSwipe"
If String.IsNullOrEmpty(value) Then
MsgBox("No value provided from swipe")
Return
End If
Try
splitValues = value.Split(separator)
If splitValues.Length <> 2 Then
MsgBox(String.Format("Splitting of swipe data did not result in 2 values. Swiped value is {0}", value))
Return
End If
' At this point, we should have an array with 2 elements in it
' Open a connection
Using connection As New OleDb.OleDbConnection(connectionString)
connection.Open()
Using Command As New OleDb.OleDbCommand
Command.CommandText = storedProcName
Command.CommandType = CommandType.StoredProcedure
Command.Connection = connection
' Assumes your proc takes 2 parameters, named swipe1 and swipe2
' Update to sane values
Command.Parameters.AddWithValue("#swipe1", splitValues(0))
Command.Parameters.AddWithValue("#swipe2", splitValues(1))
' Make the actual call to your stored procedure
Command.ExecuteNonQuery()
End Using
End Using
Catch ex As Exception
MsgBox(String.Format("Attempt to split {0} failed. {1}", value, ex))
End Try
End Sub
Sub Main()
Dim shorty As String
Dim works As String
Dim longun As String
Dim nuthin As String
shorty = "%128565?"
works = "%128565?;229584115?"
longun = "%128565?;229584115?%128565?;229584115?"
nuthin = Nothing
ProcessSwipe(shorty)
ProcessSwipe(works)
ProcessSwipe(longun)
ProcessSwipe(nuthin)
End Sub