Stored Procedure Variable (Code error I believe is there) - asp.net

I am trying to create a script to tidy all the columns and rows in SQL Server (I will be doing more than trimming but once it works I can plug into app-code I have already)
I think I am there but it does not seem to update - maybe the stored procedure is wrong? I believe the error is here.. -- I have looked around about variables in stored procedures and think it looks correct to me.
Insert statements for procedure here
UPDATE systemUsers
SET #ColumnName = #Update
WHERE ID = #ID
Full script...
Protected Sub btnTest_Click(sender As Object, e As System.EventArgs) Handles btnTest.Click
'Select the column names
Dim cn As SqlConnection = New SqlConnection()
Dim cmd As SqlCommand = New SqlCommand()
Dim dr As SqlDataReader
Dim i As Integer = 0
cn.ConnectionString = ConfigurationManager.ConnectionStrings("mySQLConnectionString").ConnectionString
cmd.Connection = cn
' this gets the colum name
cmd.CommandText = "select COLUMN_NAME FROM INFORMATION_SCHEMA.Columns where TABLE_NAME = 'systemUsers'"
'Open the connection to the database
cn.Open()
' Execute the sql.
dr = cmd.ExecuteReader()
' Read all of the rows generated by the command (in this case only one row).
CheckBoxList1.Items.Clear() 'remove all items for the new list
Do While dr.Read()
i = i + 1
Session.Item("ColumnName" & i) = dr.Item("COLUMN_NAME").ToString()
Loop
' Close your connection to the DB.
dr.Close()
cn.Close()
Dim j As Integer = 1
For j = 1 to i
cn.ConnectionString = ConfigurationManager.ConnectionStrings("mySQLConnectionString").ConnectionString
cmd.Connection = cn
cmd.CommandText = "Select * From [systemUsers]"
'Open the connection to the database
cn.Open()
' Execute the sql.
dr = cmd.ExecuteReader()
' Read all of the rows generated by the cmd (in this case only one row).
Dim vName As String = ""
If vName = "ID" Then
'skip as ID should never be edited!!
Else
Do While dr.Read()
vName = Session.Item("ColumnName" & j).ToString ' put into vName for Stored Procedure
Dim sConnString As String = System.Web.Configuration.WebConfigurationManager.ConnectionStrings("mySQLConnectionString").ConnectionString
Dim dsNames As SqlDataSource
dsNames = New SqlDataSource
dsNames.ConnectionString = sConnString
Dim sSQL As String
sSQL = "SPTidy"
dsNames.UpdateCommand = sSQL
dsNames.UpdateCommandType = SqlDataSourceCommandType.StoredProcedure
dsNames.UpdateParameters.Clear()
dsNames.UpdateParameters.Add("ID", dr.Item("ID").ToString())
dsNames.UpdateParameters.Add("Update", Trim(dr.Item(vName).ToString()))
dsNames.UpdateParameters.Add("ColumnName", vName)
dsNames.Update()
dsNames = Nothing
Loop
End If
j = j + 1
' Close your connection to the DB.
dr.Close()
cn.Close()
Next
End Sub
Stored procedure:
create PROCEDURE [dbo].[SPTidy]
#ID bigint,
#Update nvarchar(max),
#ColumnName nvarchar(max)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
UPDATE systemUsers
SET #ColumnName = #Update
WHERE ID = #ID
END

That code won't throw an error message because it's simply updating the variable. To have a dynamic column name you need to use dynamic SQL (or complicated case statements) but dynamic SQL is better in this instance.
DECLARE #sql nvarchar(max) = '';
SET #sql = N'UPDATE systemUsers SET ' + #ColumnName + N' = ' + #Update + N' WHERE ID=' + #ID
EXEC sp_executesql #sql
Hope this helps :)

Related

SQL Server procedure has too many arguments specified

I get the error
Procedure or function has to many arguments specified
but only sometimes. It's a REST API and cellphones call this function to validate the user. Today it's onli 1-2 cellphones and they make the call every second minute.
It works well most times but sometimes I get this error code.
To see what's wrong, I've made a small loop that gathers the parameters into a string. And sometimes they are two #GUID and #Datum and sometimes repeat themselves.
Here is the VB code:
Public Shared Sub validatePhone(secretKey As String, ByRef _RS As phoneData, Fnr As Integer)
Dim connStr As String = System.Configuration.ConfigurationManager.AppSettings("ConnStringSQL")
Dim Conn As SqlConnection = New System.Data.SqlClient.SqlConnection(connStr)
Dim _theString As New System.Text.StringBuilder
Try
_RS.message = ""
_RS.status = True
Dim Status As Integer = 0
Dim _GUID As Guid = New Guid(secretKey)
Try
Conn.Open()
Catch ex As Exception
End Try
cmd.Connection = Conn
Apt.SelectCommand = cmd
cmd.CommandType = CommandType.StoredProcedure
cmd.CommandText = "API2017_checkPhone"
cmd.Parameters.Clear()
cmd.Parameters.Add("#GUID", SqlDbType.UniqueIdentifier).Value = _GUID
cmd.Parameters.Add("#Datum", SqlDbType.SmallDateTime).Value = Now
For Each item As SqlParameter In cmd.Parameters
_theString.Append(item.ParameterName & ";")
Next
Apt.Fill(ds, "DataCheckPhone")
If ds.Tables("DataCheckPhone").Rows.Count > 0 Then
With ds.Tables("DataCheckPhone").Rows(0)
Status = .Item("spStatus")
If Status = 0 Then
_RS.Namn = .Item("Namn")
_RS.SalesID = .Item("SalesID")
_RS.Anlaggning = .Item("Anlaggning")
_RS.Anlnr = .Item("Anlnr")
Funktions.URLEncodeStr(_RS.Namn)
Funktions.URLEncodeStr(_RS.Anlaggning)
End If
End With
Else
Dim _Lnum As Integer
Funktions.Logg(Fnr & ": " & "Fatal error", 999, _Lnum, 0)
_RS.message = "Error 999:" & _Lnum.ToString
Return
End If
Catch ex As Exception
_RS.status = False
_RS.Anlaggning = Nothing
_RS.Anlnr = 0
_RS.Namn = Nothing
_RS.SalesID = Nothing
Dim _Lnum As Integer
Funktions.Logg(Fnr & ": " & ex.Message & "{" & _theString.ToString & "}", 999, _Lnum, 0)
_RS.message = "Error 999:" & _Lnum.ToString
Finally
ds.Tables.Clear()
Try
ds.Tables("DataCheckPhone").Dispose()
Catch ex As Exception
End Try
End Try
Try
Conn.Close()
Conn.Dispose()
Catch ex As Exception
End Try
End Sub
And here is the stored procedure:
ALTER PROCEDURE [dbo].[API2017_checkPhone]
#GUID as uniqueidentifier,
#Datum as smalldatetime
AS
DECLARE #Status AS INT
DECLARE #Anlaggning AS NVARCHAR(50)
DECLARE #Namn AS NVARCHAR(50)
DECLARE #Anlnr AS INT
DECLARE #SalesID AS uniqueidentifier
DECLARE #LockedSalesman AS BIT
DECLARE #LockedAnlaggning AS BIT
SET #Status = 0
IF EXISTS (SELECT * FROM KK2017_connectedPhones WHERE [guid] = #guid)
BEGIN
SET #status = 0
SET #salesID = (SELECT salesID FROM KK2017_connectedPhones
WHERE [guid] = #guid)
SET #Anlnr = (SELECT anlnr FROM KK2017_Säljare WHERE salesID = #salesID)
SET #Namn = (SELECT Namn FROM KK2017_Säljare WHERE salesID = #salesID)
SET #Anlaggning = (SELECT namn FROM KK2017_Anlaggning WHERE anlnr = #Anlnr)
SET #LockedSalesman = (SELECT locked FROM KK2017_Säljare WHERE salesID = #salesID)
UPDATE KK2017_Säljare
SET inloggad = #Datum
WHERE salesID = #SalesID
IF #LockedSalesman = 1
BEGIN
SET #Status = 2
END
SET #LockedAnlaggning = (SELECT locked FROM KK2017_Anlaggning
WHERE AnlNr = #Anlnr)
IF #LockedAnlaggning = 1
BEGIN
SET #status = 3
END
END
ELSE
SET #status = 1
SELECT
#Status AS spStatus,
#Anlaggning AS Anlaggning,
#anlnr AS anlnr,
#Namn AS namn,
#SalesID AS salesID
I must have done something wrong but can not see it.
If anyone has a proposal, I would be grateful.
/Claes
You have a threading issue because you have defined cmd as shared, which means there is only one instance servicing all of the incoming requests. Sometimes two threads are in the process of adding parameters at the same time, and both threads end up with four, hence the error.
The standard pattern here would be declare cmd as a local variable, and instantiate a new instance each time the function is called. The overhead to this is negligible.
Also, avoid shared variables in multithreaded applications (such as web services). There is only one copy of the variable for all users and all threads, and 99% of the time that is not what you actually want. For the other 1% usually you'd use application variables or HttpCache. In this case you should use a local variable.

Oracle Stored Procedure PLS-00306: wrong number or types of arguments

I am receiving the following oracle errors:
ORA-06550: line 1, column 7:
PLS-00306: wrong number or types of arguments in call to 'INSERT_CATEGORY'
ORA-06550: line 1, column 7:
PL/SQL: Statement ignored
I read over this error and people say that if you are passing a different value type to the stored procedure type can make this error but it doesn't seem to be the case for me.
Most of my coding is almost identical to what I have(and they worked). Only difference with this one is I am using a Boolean as well so I am not sure if that is causing the issues too.
Protected Sub BtnNew_Click(sender As Object, e As EventArgs) Handles BtnNew.Click
Dim conn As OleDbConnection = New OleDbConnection("Provider=""*******"";user id=" & strUserID & ";data source=" & strDatabase & ";password=" & strPssWd)
If Page.IsValid Then
If CatText.Text <> "" Then
Dim ClassifiedStr As New OleDbCommand
ClassifiedStr.CommandType = CommandType.StoredProcedure
'name of stored procedure = 'insert_category'
ClassifiedStr.CommandText = "insert_category"
ClassifiedStr.Connection = conn
'Must be organized based on Stored Procedure
ClassifiedStr.Parameters.Add("val_category", OleDbType.VarChar, 40).Value = CatText.Text
conn.Open()
'Makes sure the Category doesn't already exist****************
Dim myParm As OleDbParameter = ClassifiedStr.Parameters.Add("val_newcat", OleDbType.Boolean)
myParm.Direction = ParameterDirection.Output
ClassifiedStr.ExecuteNonQuery()
'myParm needs Execute
Dim standardid As Integer = myParm.Value
'***********************************************
If standardid = False Then
conn.Close()
Response.Write("<script language=""javascript"">alert('Thanks! Record Has Been Added.');</script>")
Response.Redirect("DisplayCategories.aspx")
Else
Response.Write("<script language=""javascript"">alert('Sorry! Record Already Exist.');</script>")
Exit Sub
End If
Else
Response.Write("<script language=""javascript"">alert('You must insert a record.');</script>")
Exit Sub
End If
End If
End Sub
Stored Procedure
CREATE OR REPLACE PROCEDURE insert_category
(val_category TABLENAME.Category%type,
val_newcat out boolean)
as num_catid number;
begin
select category_seq.nextval into num_catid from dual;
INSERT INTO TABLENAME
(select num_catid, val_category from TABLENAME WHERE Category != val_Category);
commit;
val_newcat := SQL%FOUND;
end;
Updates that fixed issue:
Dim ClassifiedStr As New OleDbCommand
ClassifiedStr.CommandType = CommandType.StoredProcedure
'name of stored procedure = 'insert_category'
ClassifiedStr.CommandText = "insert_category"
ClassifiedStr.Connection = conn
'Must be organized based on Stored Procedure
ClassifiedStr.Parameters.Add("val_category", OleDbType.VarChar, 40).Value = CatText.Text
conn.Open()
'Makes sure the Category doesn't already exist
Dim myParm As OleDbParameter = ClassifiedStr.Parameters.Add("val_newcat", OleDbType.VarChar, 10)
myParm.Direction = ParameterDirection.Output
ClassifiedStr.ExecuteNonQuery()
'myParm needs Execute before declared
Dim standardid As String = myParm.Value
'***********************************************
If standardid = "TRUE" Then
conn.Close()
etc....
Stored Procedure:
(val_category t_category.Category%type,
val_newcat out varchar2)
as num_catid number;
begin
select newCategory_seq.nextval into num_catid from dual;
INSERT INTO TABLENAME
select num_catid, val_category from dual WHERE not exists (select * from TABLENAME where Category = val_Category);
val_newcat := case SQL%FOUND when TRUE then 'TRUE' else 'FALSE' end;
commit;
end;

Validate that textbox has numeric value in vb.net and compare value with database

enter image description hereI'm trying to validate a textbox where users will put an ID. The ID has to be numeric and at the same time compare to a valid ID in the database. When I was just validating for numeric, I didn't have any problems. But now that I have two conditions, my code doesn't work properly. Whenever I type in letters in the textbox and click a button, it gives me an error. The boolean is throwing me off lol. Below is my code:
Thank you in advance.
Protected Sub btnGo_Click(sender As Object, e As EventArgs) Handles btnGo.Click
Dim dt As DataTable
Dim dr As DataRow
Dim Conn As New SqlConnection("Data Source=Computer;Initial Catalog=Catalog;Persist Security Info=True;User ID=userid;Password=password")
Dim cmd As New SqlCommand("SELECT COUNT(*) FROM [tbl] WHERE [ID]=#Value", Conn)
cmd.Parameters.Add("#Value", SqlDbType.NVarChar).Value = txtId.Text
Conn.Open()
Dim valueExistsInDB As Boolean = CBool(CInt(cmd.ExecuteScalar()) > 0)
Conn.Close()
If (IsNumeric(txtId.Text)) AndAlso valueExistsInDB = True AndAlso txtId.Text IsNot Nothing Then
dt = GetDataTable("SELECT ID, LEFT(SANZ_ID, PATINDEX('%.%', SANZ_ID) -1) AS City, CASE WHEN ST_DIR_ID = 1 THEN 'NB' WHEN ST_DIR_ID = 2 THEN 'SB' WHEN ST_DIR_ID = 3 THEN 'EB' WHEN ST_DIR_ID = 4 THEN 'WB' END AS ST_DIR, STREET_OF_TRAVEL, CROSS_STREET, (SELECT TOP 1 CASE WHEN STATUS_ID = 1 THEN 'F' WHEN STATUS_ID = 2 THEN 'P' WHEN STATUS_ID = 3 THEN 'I' WHEN STATUS_ID = 4 THEN 'N' WHEN STATUS_ID = 5 THEN 'A' END FROM tbl where dbo.tbl.ID=ID) AS STATUS FROM tbl WHERE ID=" & txtId.Text)
dr = dt.Rows(0)
labelStreet.Text = dr("street_of_travel")
labelCrossStreet.Text = dr("cross_street")
labelCity.Text = dr("city")
labelDir.Text = dr("st_dir")
labelAda.Text = dr("STATUS")
'dropdownStatus.SelectedValue=
dropdownStatus.Visible = True
txtNotes.Visible = True
btnSave.Visible = True
Else
MessageBox.Show("ID not found! Please input a valid ID.")
End If
End Sub
If ID is a numeric field then you should pass a numeric parameter not an NVarChar one
' First try to convert the input text to an integer '
' this should be done here before acting on the db '
Dim id As Integer
if Not Int32.TryParse(txtId.Text, id) Then
MessageBox.Show("Error, not a valid number")
return
End If
Dim cmdText = "SELECT COUNT(*) FROM [tbl] WHERE [ID]=#Value"
Using Conn = New SqlConnection(....)
Using cmd As New SqlCommand(cmdText, Conn)
cmd.Parameters.Add("#Value", SqlDbType.Int).Value = id
Conn.Open()
Dim valueExistsInDB = CBool(CInt(cmd.ExecuteScalar()) > 0)
' At this point you don't need anymore to check if the input value'
' is numeric and your if is more simple.....'
if valueExistsInDB Then
......
... continue with your code ....
Else
MessageBox.Show("ID not found! Please input a valid ID.")
End if
End Using
End Using

Insert and Update with XML in stored procedure

I need some help in using a stored procedure in my case below: I have a table with a single XML column which takes in fields VoucherCode and Quantity, the data in SQL xml column looks like this:
<CampaignVoucher xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" VoucherCode="Vouch001" Quantity="2" />
The below method will call my stored procedure to check if a particular voucher exist based on my voucher code and then either add a new row or update an existing voucher in my gridview:
Protected Sub btnAdd_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnAdd.Click
Dim dbCommand As DbCommand = Nothing
'Dim cmd As New SqlCommand()
If TextBox1.Text = "" Or DropDownList1.SelectedIndex = 0 Then
Exit Sub
End If
Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("Test").ConnectionString)
Dim da As New SqlDataAdapter("SELECT CustomerID, VoucherXML FROM Customers", con)
Dim cmd As New SqlCommand("Campaign_InsertRewardsVoucher_XML", con)
cmd.CommandType = CommandType.StoredProcedure
Dim dt As New DataTable()
da.Fill(dt)
' Here we'll add a blank row to the returned DataTable
Dim dr As DataRow = dt.NewRow()
dt.Rows.InsertAt(dr, 0)
'Creating the first row of GridView to be Editable
GridView1.EditIndex = 0
GridView1.DataSource = dt
GridView1.DataBind()
'Changing the Text for Inserting a New Record
DirectCast(GridView1.Rows(0).Cells(0).Controls(0), LinkButton).Text = "Insert"
' Serialization ----------------------------
Dim cm As New CampaignVoucher(DropDownList1.SelectedValue, TextBox1.Text)
Dim serializer As New XMLserializer(cm.[GetType]())
Dim memoryStream As New MemoryStream()
Dim writer As New XmlTextWriter(memoryStream, Encoding.UTF8)
serializer.Serialize(writer, cm)
'get the stream from the writer
memoryStream = TryCast(writer.BaseStream, MemoryStream)
'apply encoding to the stream
Dim enc As New UTF8Encoding()
Dim xml As String = enc.GetString(memoryStream.ToArray()).Trim()
' -------------------------------------------
cmd.Parameters.Add("#p1", SqlDbType.VarChar, 50).Value = DropDownList1.SelectedValue
cmd.Parameters.Add("#p2", SqlDbType.Text).Value = xml
cmd.Connection = con
con.Open()
cmd.ExecuteScalar()
con.Close()
GridView1.EditIndex = -1
BindData()
TextBox1.Text = ""
End Sub
Backtrack a little, I wrote this working stored proc as shown below for the same purpose just that it was meant for a conventional storage: 1 table with a VoucherCode and Quantity column, now with the XML column, now encapsulating both VoucherCode and Quantity values, I am lost to how to rewrite my stored proc, tried different ways but apparently I made a mess out of it, please advice, thanks!:
ALTER PROCEDURE [dbo].[Campaign_InsertRewardsVoucher]
#VoucherCode nvarchar(50) =NULL,
#Quantity int = NULL
--#ExistingQuantity int = NULL
AS
BEGIN
DECLARE #ExistingQuantity Int = Null
IF EXISTS (SELECT * FROM ForTest_Campaign_Voucher WHERE VoucherCode=#VoucherCode)
BEGIN
SET #ExistingQuantity = (SELECT Quantity from ForTest_Campaign_Voucher Where VoucherCode=#VoucherCode)
SET #ExistingQuantity = (#ExistingQuantity + #Quantity)
UPDATE ForTest_Campaign_Voucher SET VoucherCode=#VoucherCode, Quantity=#ExistingQuantity Where VoucherCode=#VoucherCode
END
ELSE
INSERT INTO ForTest_Campaign_Voucher(VoucherCode, Quantity) VALUES(#VoucherCode, #Quantity)
END
ALTER PROCEDURE [dbo].[Campaign_InsertRewardsVoucher]
#VoucherCode nvarchar(50) =NULL,
#Quantity int = NULL
AS
BEGIN
DECLARE #ExistingQuantity Int
SET #ExistingQuantity = (SELECT xmlFieldName.value('(/CampaignVoucher/#Quantity)[1]', 'int')
FROM ForTest_Campaign_Voucher
WHERE xmlFieldName.value('(/CampaignVoucher/#VoucherCode)[1]', 'nvarchar(50)') = #VoucherCode)
IF #ExistingQuantity IS NULL
BEGIN
INSERT INTO ForTest_Campaign_Voucher
(
xmlFieldName
)
VALUES
(
'<CampaignVoucher xmlns:xsd="http://www.w3.org/2001/XMLSchema" VoucherCode="' + #VoucherCode + '" Quantity="' + CAST(#Quantity AS NVARCHAR(16)) + '" />'
)
END
ELSE
DECLARE #NewQuantity INT
SET #NewQuantity = #ExistingQuantity + #Quantity
UPDATE ForTest_Campaign_Voucher
SET xmlFieldName='<CampaignVoucher xmlns:xsd="http://www.w3.org/2001/XMLSchema" VoucherCode="' + #VoucherCode + '" Quantity="' + CAST(#NewQuantity AS NVARCHAR(16)) + '" />'
WHERE xmlFieldName.value('(/CampaignVoucher/#VoucherCode)[1]', 'nvarchar(50)') = #VoucherCode
END
GO

Why no data is appearing?

I am developing an ASPX web page to return results from two SQL stored procs via VB. When I execute these two stored procs, they both return valid data. But for some reason, when I run this report it doesn't return any errors, however, it doesn't return any records/data either!
Also, I can't debug it for some reason, although I can set breakpoints! This is using VS 2008, but I think reason I can't debug is I believe this is a limited version that just works for SSRS and SSIS.
Here is an excerpt of my code:
<HTML>
<SCRIPT LANGUAGE="VB" RUNAT="Server">
Sub Page_Load(Sender as Object, E as EventArgs)
If Not IsPostback Then
Dim TheMonthDate As Date = DateAdd(DateInterval.Month, -1, Today)
calStartDate.SelectedDate = CDate((TheMonthDate.Month) & "/1/" & Year(TheMonthDate)).ToString("MM/dd/yyyy")
calEndDate.SelectedDate = GlobalFunctions.GlobalF.MonthLastDate(CDate((TheMonthDate.Month) & "/1/" & Year(TheMonthDate)).ToString("MM/dd/yyyy"))
Dim arrLevel as New ArrayList()
arrLevel.Add("All")
arrLevel.Add("Inquiries")
arrLevel.Add("All Complaints")
arrLevel.Add("Elevated Complaints")
arrLevel.Add("Non-Elevated Complaints")
dLevel.DataSource = arrLevel
dLevel.DataBind()
dLevel.selectedvalue = "All Complaints"
End If
Main
End Sub
Sub Main()
'------------------------- Query database and get arrays for the chart and bind query results to datagrid ----------------------------------------
Dim FirstMonthDate as date = calStartDate.SelectedDate
Dim LastMonthDate as date = calEndDate.SelectedDate
Dim TheLevel As Integer
Dim TitleLevel as String
Select Case dLevel.SelectedValue
Case "All"
TheLevel = 5
TitleLevel = "Inquiries and Complaints"
Case "Inquiries"
TheLevel = 0
TitleLevel = "Inquiries"
Case "All Complaints"
TheLevel = 3
TitleLevel = "All Complaints"
Case "Elevated Complaints"
TheLevel = 2
TitleLevel = "Elevated Complaints"
Case "Non-Elevated Complaints"
TheLevel = 1
TitleLevel = "Non-Elevated Complaints"
End Select
Dim DSPageData as new System.Data.DataSet
DSPageData = GlobalFunctions.GlobalF.GetComplaintTrending2(FirstMonthDate, LastMonthDate, TheLevel)
...
Dim DSDetails As New System.Data.DataSet
DSDetails = GlobalFunctions.GlobalF.GetComplaintTrendingDetails2(FirstMonthDate, LastMonthDate, TheLevel)
dgTable.DataSource = DSDetails
dgTable.DataBind()
Where in my Global.vb file I have:
'Added by Ryan on 4/17/11
Public Shared Function GetComplaintTrending2(ByVal FirstMonth As DateTime, ByVal LastMonth As DateTime, ByVal rowLevel As Integer) As DataSet
Dim DSPageData As New System.Data.DataSet
Dim param(2) As SqlClient.SqlParameter
param(0) = New SqlParameter("#FirstMonthDate", SqlDbType.DateTime)
param(0).Value = FirstMonth
param(1) = New SqlParameter("#LastMonthDate", SqlDbType.DateTime)
param(1).Value = LastMonth
param(2) = New SqlParameter("#TheLevel", SqlDbType.Int)
param(2).Value = rowLevel
''# A Using block will ensure the .Dispose() method is called for these variables, even if an exception is thrown
''# This is IMPORTANT - not disposing your connections properly can result in an unrespsonsive database
Using conn As New SQLConnection(ConfigurationSettings.AppSettings("AMDMetricsDevConnectionString")), _
cmd As New SQLCommand("ComplaintTrending2", conn), _
da As New SQLDataAdapter(cmd)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddRange(param)
da.Fill(DSPageData)
End Using
Return DSPageData
End Function
'Added by Ryan on 4/17/11
Public Shared Function GetComplaintTrendingDetails2(ByVal FirstMonth As DateTime, ByVal LastMonth As DateTime, ByVal rowLevel As Integer) As DataSet
Dim DSPageData As New System.Data.DataSet
Dim param(2) As SqlClient.SqlParameter
param(0) = New SqlParameter("#FirstMonthDate", SqlDbType.DateTime)
param(0).Value = FirstMonth
param(1) = New SqlParameter("#LastMonthDate", SqlDbType.DateTime)
param(1).Value = LastMonth
param(2) = New SqlParameter("#TheLevel", SqlDbType.Int)
param(2).Value = rowLevel
''# A Using block will ensure the .Dispose() method is called for these variables, even if an exception is thrown
''# This is IMPORTANT - not disposing your connections properly can result in an unrespsonsive database
Using conn As New SQLConnection(ConfigurationSettings.AppSettings("AMDMetricsDevConnectionString")), _
cmd As New SQLCommand("ComplaintTrendingDetails2", conn), _
da As New SQLDataAdapter(cmd)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddRange(param)
da.Fill(DSPageData)
End Using
Return DSPageData
End Function
And these stored procs are defined as:
CREATE PROCEDURE [dbo].[ComplaintTrendingDetails2]
--DECLARE
#FirstMonthDate DATETIME,
#LastMonthDate DATETIME,
#TheLevel INT
AS
SET NOCOUNT ON;
--ComplaintTrendingDetails2 '2/1/11', '2/28/11 23:59:59', 2
--SET #FirstMonthDate = '2/1/11'
--SET #LastMonthDate = '2/28/11 23:59:59'
--SET #TheLevel = '2'
SELECT DISTINCT
A.QXP_EXCEPTION_NO, A.[LEVEL], A.pRE,
A.QXP_REPORT_DATE, A.CLOSE_DATE, A.EPA_PRD_NAME,
A.EPA_PRD_CODE, A.EPL_LOT_NUMBER,
A.QXP_SHORT_DESC, A.QXP_DESCRIPTION,
A.QXP_RESOLUTION_DESC, A.CXP_CLIENT_NAME, A.Country,
C.PRODUCT, C.PRODUCT_GROUP, C.PRODUCT_ORG_UNIT,
B.DOC_DOCUMENT_NO, A.TICKET_NUM, A.CENTER_NUM,
A.COUNTRY_CODE, A.QXP_ID, B.IRF_QEI_ID
FROM ALL_COMPLAINTS A LEFT OUTER JOIN
SMARTSOLVE.V_QXP_ISSUE_REF B ON A.QXP_ID = B.IRF_QXP_ID LEFT OUTER JOIN
MANUAL.PRODUCTS C ON A.EPA_PRD_CODE = C.LIST_NUMBER
LEFT OUTER JOIN SMARTSOLVE.V_CXP_CUSTOMER_PXP D ON A.QXP_ID = D.QXP_ID
WHERE A.QXP_REPORT_DATE >= #FirstMonthDate AND A.QXP_REPORT_DATE <= #LastMonthDate
AND (A.QXP_SHORT_DESC <> 'Design Control') AND LEVEL = #TheLevel
AND (D.QXP_EXCEPTION_TYPE <> 'Non-Diagnostic' OR D.QXP_EXCEPTION_TYPE IS NULL)
ORDER BY 4
and
--ALTER PROCEDURE [dbo].[ComplaintTrending2]
DECLARE
#FirstMonthDate DATETIME,
#LastMonthDate DATETIME,
#TheLevel INT
--AS
-- SET NOCOUNT ON;
--ComplaintTrending2 '2/1/11', '2/28/11 23:59:59', 2
SET #FirstMonthDate = '2/1/11'
SET #LastMonthDate = '2/28/11 23:59:59'
SET #TheLevel = '2'
SELECT
CASE ISNULL(PRODUCT_GROUP, '') WHEN '' THEN 'Unspecified' ELSE PRODUCT_GROUP END AS PRODUCT_GROUP,
COUNT(DISTINCT A.QXP_EXCEPTION_NO) AS CountOfTickets
FROM ALL_COMPLAINTS a
LEFT OUTER JOIN MANUAL.PRODUCTS b ON a.EPA_PRD_CODE = b.LIST_NUMBER
LEFT OUTER JOIN SMARTSOLVE.V_CXP_CUSTOMER_PXP c ON a.QXP_ID = c.QXP_ID
WHERE a.QXP_REPORT_DATE >= #FirstMonthDate AND a.QXP_REPORT_DATE <= #LastMonthDate
AND (a.QXP_SHORT_DESC <> 'Design Control') AND LEVEL = #TheLevel
AND (c.QXP_EXCEPTION_TYPE <> 'Non-Diagnostic' OR c.QXP_EXCEPTION_TYPE IS NULL)
GROUP BY PRODUCT_GROUP
ORDER BY COUNT(DISTINCT a.QXP_EXCEPTION_NO) DESC
Could the problem be due to the fact that this web page uses the same SQL connection for both stored procs? The first proc should be returned initially, and the second proc after this screen. So I don't need both stored procs information simultaneously, so I would think I could reuse the same SQL connection.
OK, I found where the problem is located. If I just comment out the Level statement in the Where clause, it does return data. So only thing I changed was that one line in my SQL code and it works. This means missing data must be due to datatype incompatibility, no? What is the problem?
I think the problem is your code does not even compile. Looking at the posted page right at the start we see this:
End If
Main
End Sub
This is not valid VB. You are running an old version of your code. This is also why you can't debug it. You don't have the current one to set break points on.

Resources