ASP Sp Execution Returning Closed Recordset
Jul 20, 2005
Can anybody tell me why a) when running a stored proc from an asp page to
return a recordset the command succeeds if the sp queries an existing table
directly, but b) if the stored proc populates results into a different
table, temporary table, global temp table, or table variable, then queries
one of these, the asp page reports that the recordset object is closed. If
using a table, I have set grant, select, update, delete permissions for the
asp page user account, so it doesn't appear to be a permissioning issue. If
run in Query Analyser the sp runs fine of course.
Abridged asp code is as follows:
StoredProc = Request.querystring("SP")
oConn.ConnectionString = "Provider=SQLOLEDB etc"
oConn.Open
set oCmd = Server.CreateObject("ADODB.Command")
oCmd.ActiveConnection = oConn
oCmd.CommandText = StoredProc
oCmd.CommandType = adCmdStoredProc
oCmd.Parameters.Refresh
'code here that populates the parameters of the oCmd object correctly
Set oRs = Server.CreateObject("ADODB.Recordset")
With oRS
.CursorLocation = adUseClient
.CursorType = adOpenStatic
.LockType = adLockBatchOptimistic
'execute the SP returning the result into a recordset
.Open oCmd
End With
' Save data into IIS response object
Response.ContentType = "text/xml"
oRs.Save Response, adPersistXML
'the line above fails with stored procs from example B below, reporting "not
allowed when object is closed", but works with example A
SP Example A - this one works fine
Create Proc spTestA AS
SELECT ID FROM FileList
GO
SP Example B - this one doesn't work from ASP but runs fine in QA
Create Proc spTestB AS
DECLARE @Results Table (ID TinyInt)
INSERT INTO @Results SELECT ID FROM FileList
SELECT ID FROM @Results
GO
I can see the SP executing using profiler when the asp page is called for
both sp's above, so it doesn't appear to be a problem with the execution.
It's something to do with returning the result set from the table variable.
Thanks,
Robin Hammond
View 1 Replies
ADVERTISEMENT
Oct 8, 2015
I'm running the following SQL query from LabVIEW, a graphical programming language, using the built in capabilities it has for database connectivity:
DECLARE @currentID int
SET @currentID = (SELECT MIN(ExperimentID) FROM Jobs_t WHERE JobStatus = 'ToRun');
UPDATE [dbo].[Jobs_t]
SET [JobStatus] = 'Pending'
WHERE ExperimentID = @currentID;
SELECT @currentID AS result
<main.img>
This is the analogous code to main() is a C-like language. The first block, which has the "Connection Information" wire going into it, opens a .udl file and creates an ADO.NET _Connection reference, which is later used to invoke methods for the query.
<execute query.img>
This is the inside of the second block, the one with "EXE" and the pink wire going into it. The boxes with the gray border operate much like "switch" statements. The wire going into the "?" terminal on these boxes determines which case gets executed. The yellow boxes with white rectangels dropping down are invoke nodes and property nodes; they accept a reference to an object and allow you to invoke methods and read/write properties of that object. You can see the _Recordset object here as well. <fetch recordset.img>
Here's the next block to be executed, the one whose icon reads "FETCH ALL". We see that the first thing to execute on the far left grabs some properties of the recordset, and returns them in a "struct" (the pink wire that goes into the box that reads "state"). This is where the code fails. The recordset opened in the previous VI (virtual instrument) has a status of "closed", and the purple variant (seen under "Read all the data available") comes back empty.
The rest of the code is fairly irrelevant, as it's just converting the received variant into usable data, and freeing the recordset reference opened previously. My question is, why would the status from the query of the recordset be "closed"? I realize that recordsets are "closed" when the query returns no rows, but executing that query in SSMS returns good data. Also, executing the LabVIEW code does the UPDATE in the query, so I know that's not broken either.
View 3 Replies
View Related
Sep 29, 2000
Is possible use DTS for return Data in recordset in the VB ?
I am asking this , why I have access the database INFORMIX, and several things do not work with Stored Procedure in the Informix
thank you in advance
View 1 Replies
View Related
Sep 13, 2004
Hi, I have a table that has the following field and results.
I want a where clause that returns records that start 0000........
I need to exclude those records that start 0001..........
Can anyone help
oseq
-------
0000
0000.0000
0000.0000.0000
0000.0000.0000.0000
0000.0000.0000.0000.0000
0000.0000.0000.0000.0001
0000.0000.0000.0001
0000.0000.0001
0001
0001.0000
0001.0001
0001.0002
0000.0000.0002
0000.0000.0003
0000.0001
0000.0001.0000
0000.0001.0000.0000
0000.0001.0000.0000.0000
0000.0001.0000.0000.0000.0000
0000.0026.0004.0009
0000.0026.0004.0010
View 3 Replies
View Related
Mar 7, 2008
I need to return a rowset from a stored procedure. The returned rows will have ten columns and need to be bound to a gridview. Here is a code snippet.
'Create a DataAdapter, and then provide the name of the stored procedure.MyDataAdapter = New SqlDataAdapter("TMPTABLE_QUERY", MyConnection)
'Set the command type as StoredProcedure.
MyDataAdapter.SelectCommand.CommandType = CommandType.StoredProcedure
'Create and add a parameter to Parameters collection for the stored procedure.MyDataAdapter.SelectCommand.Parameters.Add(New SqlParameter("@condition_cl", _
SqlDbType.VarChar, 100))
'Assign the search value to the parameter.MyDataAdapter.SelectCommand.Parameters("@condition_cl").Value = sqlwhere & orderby
'ASSIGN THE OUTPUT PARAMETERS. HERE IS WHERE I NEED HELP (?????????????????)
DS = New DataSet() 'Create a new DataSet to hold the records.
MyDataAdapter.Fill(DS, "TMPTABLE_QUERY") 'Fill the DataSet with the rows returned.
'Set the data source for the DataGrid as the DataSet that holds the rows.GridView1.DataSource = DS.Tables("TMPTABLE_QUERY").DefaultView
GridView1.DataBind()
MyDataAdapter.Dispose() 'Dispose of the DataAdapter.
MyConnection.Close()
In my little research, I have seen examples of how to return a single value, but not multiple rows. I essentially have two problems. I'm not sure how my output parameters are to be defined and added. Do I need a separate 'Parameters.Add' statement for each column field value returned or can I do a single 'Parameters.Add' statement to define the whole row as an output parameter? Also, upon returning from the call to the SP, will I need a looping mechanism to populate the recordset for each individual record returned, or will the 'MyDataAdapter.Fill(DS, "TMPTABLE_QUERY") suffice, as included in my code above?
Thanks in advance.
View 3 Replies
View Related
Jul 12, 2000
HELP HELP HELP!!
I have two questions.
I'm using VB 6.0 with ADO to SQL 7.0. My stored procedure works fine with Query Analyzer. I pass one parameter.
sp_test "1234"
And I get a recordset returned.
The stored procedure looks like this:
CREATE PROCEDURE sp_test
@facility_key varchar(255) = null
AS
/*DECLARE @sql1 varchar(255)*/
SELECT * FROM v_reimbursement_report
WHERE facility_key = @facility_key
/*IF @facility_key <> null
PRINT "0"
BEGIN
SELECT * FROM v_reimbursement_report
WHERE facility_key = @facility_key
END*/
When I uncomment the commented lines, I can still get a recordset returned using the query analyzer. And I get the same recordset returned when I use VB ADO and leave the stored proc lines commented out. However, when I call the procedure using the same VB code with the stored proc lines uncommented, I get -1 returned for rs.recordcount:
Private Sub Main_Click()
On Error GoTo Err_Main
Dim lsFacility As String
Dim lsReportName As String
Dim rs As ADODB.Recordset
Dim cmd As ADODB.Command
Dim gconn As ADODB.Connection
Dim param_facility_key As ADODB.Parameter
Dim gConnString As String
gConnString = "Trusted_Connection=Yes;UID=sa;PWD=yoyo;DATABASE=y ada;SERVER=ya;Network=dbnmpntw;Address=ya;DRIVER={ SQL Server};DSN=''"
Set gconn = New ADODB.Connection
Set rs = New ADODB.Recordset
Set cmd = New ADODB.Command
gconn.Open gConnString
cmd.Parameters.Refresh
lsFacility = "1234"
Set param_facility_key = cmd.CreateParameter("facility_key", adVarChar, adParamInput, 255)
cmd.Parameters.Append param_facility_key
param_facility_key.Value = lsFacility
cmd.CommandType = adCmdStoredProc
cmd.CommandText = "sp_reimbursement_report_test"
cmd.Name = "sp_reimbursement_report_test"
Set cmd.ActiveConnection = gconn
rs.Open cmd, , adOpenKeyset, adLockOptimistic
MsgBox rs.RecordCount
Exit_Main:
Screen.MousePointer = vbNormal
gconn.Close
rs.Close
Exit Sub
Err_Main:
Screen.MousePointer = vbNormal
MsgBox "Error " & Err.Number & " has occurred: " & Err.Description
End Sub
Here are my questions:
1. Why don't I get a recordset returned to VB if I have anything (the commented lines) except a simple SELECT statement in the stored proc.
2. Why must I do a Print "0" (or anything) command in the stored procedure within the IF statement to see a recordset return?
TIA for any help you can give....this one has been keeping me up....and my company down.
JWB
View 3 Replies
View Related
Apr 2, 2000
Dear all,
I have a big problem in using SQL Server stored procedures:
When I have two select statement in the same procedure, the first one will use for returning specific information for the second one to select appropiate result to the client, but the stored procedure just return the first select statement recordset! What can I do? (I use VB Data Environment to access the stored procedures)
View 2 Replies
View Related
Oct 19, 2005
Is there a server variable which will tell me how long the server took in returning a particular recordset. I've looked through MSDN SQL 2000 articles and could'nt / did'nt see anything. Or perhaps there is another way? Thanks!
View 1 Replies
View Related
Jun 12, 2008
The stored procedure I created returns all records from the table if no parameters are passed, as expected. When I pass in the only parameter, I get 0 records returned when there should be one or more returned. I'm sure it's something simple in my syntax, but I don't see it.
This call returns all records:
exec webservices_BENEFICIAL_USES_DM_SELECT
This call returns 0 records, when it should return 1:
exec webservices_BENEFICIAL_USES_DM_SELECT @DISPOSAL_AREA_NAME='Cell 8'
Here is the stored procedure:
ALTER PROCEDURE [dbo].[webservices_BENEFICIAL_USES_DM_SELECT]
-- Add the parameters for the stored procedure here
@DISPOSAL_AREA_NAME DISPOSAL_AREA_NAME_TYPE = NULL
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
IF @DISPOSAL_AREA_NAME IS NULL
BEGIN
SELECT*
FROMBENEFICIAL_USES_DM
END
ELSE
BEGIN
SELECT*
FROMBENEFICIAL_USES_DM
WHEREDISPOSAL_AREA_NAME = '@DISPOSAL_AREA_NAME'
END
END
View 4 Replies
View Related
Jul 23, 2005
Hi All. My question is this. I have a complex stored procedure in SQLServer which works fine when I run it in Query Analyzer. However, whenI call it within my ASP script, it returns nothing, and sometimes locksup. If I change my script to call other existing stored procedures itworks fine. It's just with this particular stored proc. I have triedvarious DB calls in ASP, such as opening the recordset through an ADOconnection and through the Command object but to no avail. Here is mySQL:SET QUOTED_IDENTIFIER OFFGOSET ANSI_NULLS OFFGOALTER PROCEDURE dbo.sp_getProfessionalsByTypeID@typeID intASdeclare @catID intdeclare @userID intdeclare @strUserName varchar(100)declare @strFirstName varchar(100)declare @strLastName varchar(100)declare @strTypeName varchar(100)declare @strCategoryName varchar(100)declare @strPictureURL varchar(100)declare @sql varchar(1000)declare @a varchar(100)declare @b varchar(100)declare @c varchar(100)declare @d varchar(100)beginset @a=''set @b=''set @c=''set @d=''--Create Temp TableCREATE TABLE #QueryResult (nCatID int, nTypeID int, nUserID int,strUserName varchar(100), strFirstName varchar(100), strLastNamevarchar(100), strTypeName varchar(100), strCategoryNamevarchar(100),strPictureURL varchar(100))--Search QuerybeginINSERT #QueryResultSELECTdbo.tbl_musician_type.nCatID, dbo.tbl_musician_type.nTypeID,dbo.tbl_users.nUserID, dbo.tbl_users.strUserName,dbo.tbl_users.strLastName,dbo.tbl_users.strFirstName,dbo.tbl_musician_type.strTypeName, dbo.tbl_category.strCategoryName,dbo.tbl_professionals.strPictureURLFROMdbo.tbl_musician_type INNER JOINdbo.tbl_category ON dbo.tbl_musician_type.nCatID= dbo.tbl_category.nCategoryID INNER JOINdbo.tbl_profile ONdbo.tbl_musician_type.nTypeID = dbo.tbl_profile.nTypeID INNER JOINdbo.tbl_users ON dbo.tbl_profile.nUserID =dbo.tbl_users.nUserID LEFT OUTER JOINdbo.tbl_professionals ON dbo.tbl_users.nUserID= dbo.tbl_professionals.nUserIDWHEREdbo.tbl_musician_type.nTypeID = @typeIDend--Create Temp TableCREATE TABLE #QueryResult2 (ID int IDENTITY,nCatID int, nTypeID int,nUserID int, strUserName varchar(100), strFirstName varchar(100),strLastName varchar(100), strTypeName varchar(100), strCategoryNamevarchar(100),strPictureURL varchar(100), strArtist varchar(100),strAlbumTitle varchar(100), strRecordLabel varchar(100), strYearvarchar(100))--Now Declare the Cursor for Speakersdeclare cur_musicians CURSOR FOR--Combined Results Groupedselect distinct nCatID, nTypeID, nUserID, strUserName, strLastName,strFirstName, strTypeName, strCategoryName, strPictureURLFrom #QueryResultopen cur_musiciansfetch next from cur_musicians INTO @catID, @typeID, @userID,@strUserName, @strLastName, @strFirstName, @strTypeName,@strCategoryName, @strPictureURL--Loop Through Cursorwhile @@FETCH_STATUS = 0beginSELECT TOP 1 @a = strArtist, @b=strAlbumTitle,@c=strRecordLabel, @d=strYearFROM dbo.tbl_profile_discogwhere nTypeID = @typeID AND nCategoryID = @catID AND nUserID =@userIDinsert #QueryResult2select @catID as nCatID, @typeID as nTypeID, @userID as nUserID,@strUserName as strUserName, @strLastName as strLastName, @strFirstNamestrFirstName, @strTypeName as strTypeName, @strCategoryName asstrCategoryName, @strPictureURL as strPictureURL, @a ashighlightArtist, @b as highlightAlbumTitle, @c as highlightRecordLabel,@d as highlightYearfetch next from cur_musicians INTO @catID, @typeID, @userID,@strUserName, @strLastName, @strFirstName, @strTypeName,@strCategoryName, @strPictureURLset @a = ''set @b=''set @c=''set @d=''endselect * from #QueryResult2 TI--Clean Upclose cur_musiciansdeallocate cur_musiciansdrop table #QueryResultdrop table #QueryResult2endGOSET QUOTED_IDENTIFIER OFFGOSET ANSI_NULLS ONGO
View 5 Replies
View Related
Sep 24, 2003
I'm having trouble getting a recordset out of stored procedure in ADO. The SP executes without errors, but the recordset object I return into is always closed.Here is my code:
<%
......
Set cmm = Server.CreateObject("ADODB.Command")
Set cmm.ActiveConnection = Connect
cmm.CommandType = adCmdStoredProc
cmm.CommandText = "dbo.client_updates_proc"
cmm.Parameters.Refresh
cmm.Parameters(1) = client_id
Set logRS = cmm.Execute()
if not logRS.EOF then
......
%>
My SP has one parameter, which I set above, and it ends with a select statement. When I run the SP in Query Analyzer, it outputs the table of results as is should, but I always get an error on 'if logRS.EOF then', saying that the object is closed.
View 3 Replies
View Related
Jul 20, 2005
Hi, not too swift with anything other than simple SQL statements, soI'm looking for some help.Using SQL Server 2000 with this stored proc:(@varCust varchar(50))ASSET NOCOUNT ONSELECT d.WorkOrder, d.Customer, d.SerialNo, d.Assy, d.Station,d.WIdoc,d.Start, d.StartUser, d.Finish, d.FinishUserFROM tblWorkOrder w, tblDocs dWHERE w.WorkOrder IS NULL AND w.WorkOrder = d.WorkOrder ANDd.Customer = @varCustGOI'm trying to get a complete dataset so I can simply apply it as thedatasource to a datagrid in asp.net. I need to include a 'TimeSpan'column that is the difference between d.Start and d.Finish. I alsoneed it to present in hh:mm:ss format in the datagrid column. (A) isit possible to do this within the stored proc, and (B) how would "I"do that?Thanks!Kathy
View 6 Replies
View Related
Oct 7, 2014
Following is the query that I'm running:
create table a (id int, name varchar(10));
create table b(id int, sal int);
insert into a values(1,'John'),(1,'ken'),(2,'paul');
insert into b values(1,400),(1,500);
select *
from a
cross apply( select max(sal) as sal from b where b.id = a.id)b;
Below is the result for the same:
idname sal
1John500
1ken500
2paulNULL
Now I'm not sure why the record with ID 2 is coming using CROSS APPLY, shouldn't it be avoided in case of CROSS APPLY and only displayed when using OUTER APPLY.
One thing that I noticed was that if you remove the Aggregate function MAX then the record with ID 2 is not shown in the output. I'm running this query on SQL Server 2012.
View 6 Replies
View Related
Jun 14, 2007
Hi all -
I know this is prolly an old one but I would certainly appreciate some assistance =)
environment:
SERVER (IIS6, .NET2.0, SQL2005)
CLIENT (WIN2000,IE6,VBScript)
I have an aspx that is invoking ado on the clientside. I read somewhere that javascript does not support connecting to SQL clientside. I may be wrong. In any case I am using VBScript on the client.
I am using something like this to invoke the script
Code Snippet
<a href="#" onclick="doReport()">Click Here</< FONT>a>
doReport() looks something like this ...
Code Snippet
' ========================================================
sub doReport()
Dim stSQL, rs, oWord, oDoc, oRng
Dim stCurrentSection, stTemplatePath, dtNow, dtSOR, dtLastDataPoint
Dim iLastDataPoint
set oWord = CreateObject("Word.Application")
stTemplatePath = "http://crivm-ccdev/ccprocharts/supportfiles/CCWordReport.doc"
set oDoc = oWord.Documents.Open(stTemplatePath)
oWord.visible = true
stCurrentSection = "a"
loadDebug
'loadLive
openConnection()
' == THIS DB CALL GETS 2 RESULT SETS
'set rs = getrsCustomerInfoReport(mstUnits, left(mstCycles,3), mstAppName)
set rs = getReadOnlyRS("sCC_GetCustInfo_Report '" & mstUnits & "','" & left(mstCycles,3) & "','" & mstAppName & "'")
' == POPULATE VARS FROM 1st RESULT SET
dtLastDataPoint = rs(0)
iLastDataPoint = rs(1)
set rs = rs.NextRecordset ' <== THIS IS WHERE IS ERROR IS
msgbox rs(0)
end sub
here is my openconnection sub ... oConn is global
Code Snippet
<script type="text/vbscript" language="vbscript">
'== Cursor Location
CONST adUseClient = 3
CONST adUseServer = 2
' == Cursor Type
CONST adOpenStatic = 3
CONST adOpenForwardOnly = 0
CONST adOpenDynamic = 2
' == Lock Type
CONST adLockReadOnly = 1
CONST adLockOptimistic = 3
CONST adLockPessimistic = 2
' ========================================================
sub openConnection()
Dim stConn
set oConn = CreateObject("ADODB.Connection")
'stConn = "DRIVER={sql server};Server=crivm-ccdevsql2005;Database=catcheck;Integrated Security=SSPI"
stConn = "Provider=SQLOLEDB;Server=crivm-ccdevsql2005;Database=catcheck;Integrated Security=SSPI"
'msgbox oConn.state & vbcrlf & stConn1
oConn.open(stConn)
'msgbox oConn.state
ApplySecurity
end sub
' ============================================================
Sub ApplySecurity
'gbhasDBAccess is a global variable on both client and server sides.
'Server side is set in seccheck.asp, which should be at the top of every page
'Client side is set in ApplySecurity() of ConnectServer.asp
Dim appRole
appRole = "appWriters,(tsvc123)"
oConn.Execute "sp_setapprole '" & split(appRole,",")(0) & "','" & split(appRole,",")(1) & "'"
End Sub
</< FONT></script>
Before we moved to SQL2005 I always used this
Code Snippet
' ========================================================
Function getReadOnlyMultRS(strSQL)
set rs = CreateObject("ADODB.Recordset")
rs.CursorLocation = adUseClient
rs.Open strSQL, oConn, adOpenForwardOnly, adLockReadOnly
'Disconnect the Recordset
Set rs.ActiveConnection = Nothing
'Return the Recordset
Set getReadOnlyMultRS = rs
End Function
and this always allowed me to use set rs = rs.nextresultset
but now that we switched to SQL2005 it does not seem to work. I have verified in sql studio that this sp does indeed return 2 resultsets
View 4 Replies
View Related
Jul 20, 2005
I posted this in the MS Access group, but no luck.------------------------------------------I've got another stored procedure in the same app that returns multiplerecordsets and the code works.But now I've written another SP and the code traps out with the 3251 message.The SP is writing two recordsets.When I run the SP in Query Analyzer, both recordsets appear.But when I step through the code, when the first RS should be there, it's"Closed" and nothing I've tried will make it open.Provider=SQLOLEDB.1 (which works on the other screen...)Seems like I've been here before, but I can't remember what the problem was.--PeteCresswell
View 7 Replies
View Related
Aug 23, 2007
after moving off VS debugger and into management studio to exercise our SQLCLR sp, we notice that the 2nd execution gets an error suggesting that our static SqlCommand object is getting reused from the 1st execution (of the sp under mgt studio). If this is expected behavior, we have no problem limiting our statics to only completely reusable objects but would first like to know if this is expected? Is the fact that debugger doesnt show this behavior also expected?
View 4 Replies
View Related
Sep 25, 2007
I am opening a simple command against a view which joins 2 tables, so that I can return a column which is defined as a tinyint in one of the tables. The SELECT looks like this:
SELECT TreatmentStatus FROM vwReferralWithAdmissionDischarge WHERE ClientNumber = 138238 AND CaseNumber = 1 AND ProviderNumber = 89
The TreatmentStatus column is a tinyint. When I execute that above SQL SELECT statement in SQL Server Management Studio (I am using SQL Server 2005) I get a value of 2. But when I execute the same SQL SELECT statement as a part of a SqlDataReader and SqlCommand, I get a return data type of integer and a value of 1.
Why?
View 5 Replies
View Related
Sep 12, 2007
thx but this code not needed anymore
sry
View 1 Replies
View Related
Dec 7, 2005
Hi I am slowly getting to grips with SQL Server. As a part of this, I have been attempting to work on producing more efficient queries. This post is regarding what appears to be a discrepancy between the SQL Server execution plan and the actual time taken by a query to run. My brief is to produce an attendance system for an education establishment (I presume you know I'm not an A-Level student completing a project :p ). Circa 1.5m rows per annum, testing with ~3m rows currently. College_Year could strictly be inferred from the AttDateTime however it is included as a field because it a part of just about every PK this table is ever likely to be linked to. Indexes are not fully optimised yet. Table:CREATE TABLE [dbo].[AttendanceDets] ([College_Year] [smallint] NOT NULL ,[Group_Code] [char] (12) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,[Student_ID] [char] (8) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,[Session_Date] [datetime] NOT NULL ,[Start_Time] [datetime] NOT NULL ,[Att_Code] [char] (1) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ) ON [PRIMARY]GO CREATE CLUSTERED INDEX [IX_AltPK_Clust_AttendanceDets] ON [dbo].[AttendanceDets]([College_Year], [Group_Code], [Student_ID], [Session_Date], [Att_Code]) ON [PRIMARY]GO CREATE INDEX [All] ON [dbo].[AttendanceDets]([College_Year], [Group_Code], [Student_ID], [Session_Date], [Start_Time], [Att_Code]) ON [PRIMARY]GO CREATE INDEX [IX_AttendanceDets] ON [dbo].[AttendanceDets]([Att_Code]) ON [PRIMARY]GOALL inserts are via an overnight sproc - data comes from a third party system. Group_Code is 12 chars (no more no less), student_ID 8 chars (no more no less). I have created a simple sproc. I am using this as a benchmark against which I am testing my options. I appreciate that this sproc is an inefficient jack of all trades - it has been designed as such so I can compare its performance to more specific sprocs and possibly some dynamic SQL. Sproc:CREATE PROCEDURE [dbo].[CAMsp_Att] @College_Year AS SmallInt,@Student_ID AS VarChar(8) = '________', @Group_Code AS VarChar(12) = '____________', @Start_Date AS DateTime = '1950/01/01', @End_Date as DateTime = '2020/01/01', @Att_Code AS VarChar(1) = '_' AS IF @Start_Date = '1950/01/01'SET @Start_Date = CAST(CAST(@College_Year AS Char(4)) + '/08/31' AS DateTime) IF @End_Date = '2020/01/01'SET @End_Date = CAST(CAST(@College_Year +1 AS Char(4)) + '/07/31' AS DateTime) SELECT College_Year, Group_Code, Student_ID, Session_Date, Start_Time, Att_Code FROM dbo.AttendanceDets WHERE College_Year = @College_YearAND Group_Code LIKE @Group_CodeAND Student_ID LIKE @Student_IDAND Session_Date <= @End_DateAND Session_Date >=@Start_DateAND Att_Code LIKE @Att_CodeGOMy confusion lies with running the below script with Show Execution Plan:--SET SHOWPLAN_TEXT ON--Go DECLARE @Time as DateTime Set @Time = GetDate() select College_Year, group_code, Student_ID, Session_Date, Start_Time, Att_Code from attendanceDetswhere College_Year = 2005 AND group_code LIKE '____________' AND Student_ID LIKE '________'AND Session_Date <= '2005-11-16' AND Session_Date >= '2005-11-16' AND Att_Code LIKE '_' Print 'First query took: ' + CAST(DATEDIFF(ms, @Time, GETDATE()) AS VarCHar(5)) + ' milli-Seconds' Set @Time = GetDate() EXEC CAMsp_Att @College_Year = 2005, @Start_Date = '2005-11-16', @End_Date = '2005-11-16' Print 'Second query took: ' + CAST(DATEDIFF(ms, @Time, GETDATE()) AS VarCHar(5)) + ' milli-Seconds'GO --SET SHOWPLAN_TEXT OFF--GOThe execution plan for the first query appears miles more costly than the sproc yet it is effectively the same query with no parameters. However, my understanding is the cached plan substitutes literals for parameters anyway. In any case - the first query cost is listed as 99.52% of the batch, the sproc 0.48% (comparing the IO, cpu costs etc support this). BUT the text output is:(10639 row(s) affected) First query took: 596 milli-Seconds (10639 row(s) affected) Second query took: 2856 milli-SecondsI appreciate that logical and physical performance are not one and the same but can why is there such a huge discrepancy between the two? They are tested on a dedicated test server, and repeated running and switching the order of the queries elicits the same results. Sample data can be provided if requested but I assumed it would not shed much light. BTW - I know that additional indexes can bring the plans and execution time closer together - my question is more about the concept. If you've made it this far - many thanks.If you can enlighten me - infinite thanks.
View 10 Replies
View Related
Aug 3, 2007
Hello :
How to execute a procedure stored during execution of the report, that is before the poster the data.
Thnak you.
View 4 Replies
View Related
Jun 7, 2008
I have an sp, which has 2 select statements, so iam using a sqldatareader and binding the data to a dropdown.
the first binding is fine, but when i say dataReader.NextResult(), It is null.It says the reader is closed. Can any one tell a work around for this.
thanx in advance,
Anil Kumar.
View 6 Replies
View Related
May 5, 2004
i am running a java program in tomcat to connect SQL Server,using the Microsoft's jdbc driver ,as the following code :
import java.sql.*;
class Bkjz{
ResultSet rs=null;
String spde;
String condition;
Connection con=null;
Statement sql;
public String getSpde(){
return spde;
}
public void setSpde(String spde){
this.spde=spde;
}
public ResultSet Searchsjk(){
try {
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
con=DriverManager.getConnection("jdbc:microsoft:sqlserver://localhost:1433;databasename=zkbm","zkbm","zkbm");
sql=con.createStatement(ResultSet.TYPE_SCROLL_SENS ITIVE,ResultSet.CONCUR_READ_ONLY);
if(spde.equals(""))
condition="select CRCC,CRNM,SPDE,SPNM from SPCR where EMTP='5'group by SPDE,SPNM,CRCC,CRNM";
else
condition="select CRCC,CRNM,SPDE,SPNM from SPCR where SPDE='"+spde+"'"+"and EMTP='5' group by SPDE,SPNM,CRCC,CRNM";
rs=sql.executeQuery(condition);
//con.close();
if(!rs.next())
{
return null;
}
else
{
rs.previous();
return rs;
}
}
catch(Exception e){
message="exception!!! "+e.toString();
System.out.println(e);
return null;
}
}
}
public class Bk{
public static void main(String args[]){
Bkjz bbb=new Bkjz();
bbb.setSpde("1020110");
try{
ResultSet rr=bbb.Searchsjk();
while(rr.next()){
System.out.println(rr.getString("CRCC"));
}
}
catch(Exception e){
System.out.println(e);
}
}
}
without con.close(),it can return Resultset ,but when includeing con.close(),an Exception tell me:Object has been closed, in other programms i've close connection,but it never throws this Exception,why? thanks
View 1 Replies
View Related
Jan 27, 2007
I have the Function, that fires from onLoad even of one of the asp:Label controls on my main page.
Here is it's code:
SqlConnection conn = new SqlConnection(); conn.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["UkraineConnectionString"].ToString(); SqlCommand comm = new SqlCommand("SELECT [Greeting] FROM [Misc]", conn);
try { conn.Open(); } catch { Response.Write("Error opening connection in Page_Load of default.aspx to retrieve the greetings"); }
string MyGreet = (string)comm.ExecuteScalar();
Greetings.Text = MyGreet;
try { conn.Close(); } catch { Response.Write("Error closing connection in Page_Load of default.aspx after retrieving the greetings"); } }
When it gests to conn.Open() in the debugging mode I see that the ServerVersion = 'conn.ServerVersion' threw an exception of type 'System.InvalidOperationException'.
The most interesting thing is that it used to work before.
Here is the connection string it retrieves fine.
"Data Source=MDM1;AttachDbFilename=|DataDirectory|Ukraine.mdf;Integrated Security=True;User Instance=True" providerName="System.Data.SqlClient"
As I said it used to work, but one day I tried to access the web site and it said this error that I get, that the connection is closed. Then I was using the SQL Server Express. When in the Visual studio if I would run this same site in debug, everything was working fine. I decided to uninstall the SQL Express and installed the SQL Server.
If I open the SQL Server Managment Studio in the Server name field I see MDM1(this is the name of the PC, but probably it is the same name for the Server. Well, in the MAnagment Studio it conects fine to the MDM1 so it is no probably the naming problem. Ithink it has something to do with permisssions.
If someon can - please help. Thanks.
View 3 Replies
View Related
Jan 30, 2007
Hello,
I have built a system, that uses a .dll file for all SQL operations. So a program looks something like this:
using myDLL;
....
SQLDBCON mSQL = new SQLDBCON();
and here comes the rest of the program.
My question is, the dll file has all stored procedures and when you declare mSQL as shown above, then it opens a thread to the database for that user.
Is that thread properly closed when the site has finished loading?
in my .aspx page i dont have a function like mSQL.CloseDB();
and if i try to add something like this to the dll file
~SQLDBCON {
m_local_con.Close();m_local_con.dispose();
}
i get a error message says something that this is not allowed.
Just want to know if my thread in the dll file is properly closed?
View 9 Replies
View Related
Jan 13, 2000
That is an app ACCESS 2000 wih Named Pipe ODBC to SQL Server 6.5.
After 10 minutes without use this app, the connection closed !
Have-you idea for correct this probleme ?
Regards
Alain
View 2 Replies
View Related
May 3, 2006
I'm getting object closed when returning a recordset from a stored procedure. I've tested the select statement in Query Analyzer and a value is getting returned. So, I'm not sure if my code for my stored procedure is incorrect?
Here is the code for the procedure:
CREATE Procedure dbo.GetRepEmailByZip
@sessionid varchar(50),
@zip varchar(5)
AS
Begin Transaction
INSERT INTO dbo.SupportRequests(firstname,lastname,schoolname, address,city,state,zip,phone,email,currentcustomer ,implementationtype,producttype,comment)
(SELECT FirstName,LastName,SchoolName,Address,City,State,Z ip,Phone,Email,CurrentCustomer,ImplementationType, ProductType,Comment
FROM dbo.Temp_ContactInfo
WHERE sessionid = @sessionid)
--If Transacation fails, stop execution of procedure, return error code and Rollback Transaction
IF @@ERROR<>0 OR @@RowCount = 0
BEGIN
ROLLBACK TRANSACTION
--return value
RETURN 1
END
--If Transaction succeeds, commit transaction, continue and process the select statement
COMMIT TRANSACTION
SELECT r.email
FROM PostalCodes p
INNER JOIN TerritoryList z ON p.ZipID = z.ZipID
INNER JOIN RepList r ON r.RepID = z.RepID
WHERE p.ZipCode = @zip
GO
This is the code I'm calling to execute the procedure and return the recordset:
set GetRepEmail = Server.CreateObject("ADODB.Command")
With GetRepEmail
.ActiveConnection = MM_DBConn_STRING
.CommandText = "dbo.GetRepEmailByZip"
.CommandType = 4
.CommandTimeout = 0
.Prepared = true
.Parameters.Append .CreateParameter("@RETURN_VALUE", 3, 4)
.Parameters.Append .CreateParameter("@sessionid", 200, 1,50,usrid)
.Parameters.Append .CreateParameter("@zip", 200, 1,5,zip)
set RepEmail = .Execute()
End With
Dim x, y
x = RepEmail.RecordCount
y = RepEmail.State
Response.Write(x)
Response.Write("<br>")
Response.Write(y)
'Response.Write(RepEmail("email"))
Response.End()
I'm getting "Operation is not allowed when the object is closed", which is occuring on the following line:
x = RepEmail.RecordCount
I'm trying to determine if this is problem within my procedure or in the application code.
Thanks in advance for any help.
View 4 Replies
View Related
Feb 22, 2007
In a previous post I asked the question relating to moving a file assoicated with a connection. It appears I need to close the connection first.
On advice, in a script task I created the following:
Dim dtsConnection As Microsoft.SqlServer.Dts.Runtime.ConnectionManager
For Each dtsConnection In Dts.Connections
Dim LiveConnection As Object = dtsConnection.AcquireConnection(Nothing)
Dts.Events.FireInformation(0, "", "Connection Name : " + dtsConnection.Name, "", 0, False)
dtsConnection.ReleaseConnection(LiveConnection)
dtsConnection.Dispose()
Next
Dts.TaskResult = Dts.Results.Success
RetainSameConnection is set to true.
The dispose line is something I've added just to try - I've tried it without this line as well.
The next component then moves the file and fails complaining that the file is in use.
What can I do?
Regards
Guy
View 2 Replies
View Related
Jan 5, 2006
Wierd problem here
As one user, when i select * from sys.conversation_endpoints I can see all (I assume) conversations in all states specifically DO, DI and CD
However when I change to another user I see only DI
Why is this?
If it is a permissions issue what permission do I have to grant to a user to see all conversations in sys.conversation.endpoints?
View 1 Replies
View Related
Jan 10, 2007
I hvae a stored procedure that has this at the end of it:
BEGIN
EXEC @ActionID = ActionInsert '', @PackageID, @AnotherID, 0, ''
END
SET NOCOUNT OFF
SELECT Something
FROM Something
Joins…..
Where Something = Something
now, ActionInsert returns a Value, and has a SELECT @ActionID at the end of the stored procedure.
What's happening, if that 2nd line that I pasted gets called, 2 result sets are being returned. How can I modify this SToredProcedure to stop returning the result set from ActionINsert?
View 2 Replies
View Related
Apr 16, 2007
I have a page that I have 3 connections. I've made sure that each of these are closed when they are not being used and opened just right before being used. I keep getting the error "There is already an open DataReader associated with this Command which must be closed first." This error might show up as being produced by a dataadapter or sqldatareader...I have many. I've even tried to make separate connections as some have mentioned for each...leaving me with 15+ connections. I have added "MultipleActiveResultSets=True" to the connection strings as some have mentioned. I just don't know where to go from here...
Is it possible that the problem lies in multiple instances of this page being opened? Also, the data refreshes every 15 seconds. I really need this to work, but I have no clue on how to fix this problem. The error is easy to reproduce by opening up multiple instances, but some of the times is doesn't give an error at all?!
View 4 Replies
View Related
Jun 18, 2001
Hello all,
I'm writing some stored procedures that first do an Insert or an Update, and then also do a Select to return a Recordset back to an ADO client. However an Insert or Update causes a closed recordset to be produced in ADO. I can skip over the closed recordset with the NextRecordset method.
So the question is, is there any way of stopping the closed recordset being returned? I don't want to have to call the NextRecordset method from ADO as this would mean that the client would need to know about the implementation of the stored procedure.
Has anyone got any ideas on how to get round this?
Thanks
Dave Sykes
View 2 Replies
View Related
Oct 15, 2007
I have gathered from reading online that I need to create a 2nd connection to SQL Server if I want to insert records into the database while in a "while (reader.Read())" loop.
I am trying to make my code as generic as possible, and I don't want to have to re-input the connection string at this point in my code. Is there a way to generate a new connection based on the existing open one? Or should I just create 2 connections up front and carry them around with me like I do for the 1 connection now?
Thanks.
View 7 Replies
View Related
Jan 5, 2013
Finding the court cases where all children associated with that case have a programClosureDate. I can run this query:
CaseInfo Table
CaseID,
CaseNumber,
CaseName
CaseChild Table
CaseID, FK to CaseInfo
ChildPartyID, FK to PartyID in Party table
ProgramClosureDate
Party Table
ID,
PartyID,
Firstname,
LastName
SELECT ci.CaseNumber, ci.CaseName, p.firstname+' '+p.lastname AS child, cc.programClosureDate
FROM CaseInfo ci JOIN
CaseChild cc ON ci.CaseID = cc.CaseID JOIN
Party p ON cc.ChildPartyID = p.PartyID
WHERE cc.ProgramClosureDate IS NOT NULL
ORDER BY ci.CaseName
But this does not give me the cases where all the children have programCLosureDate IS NOT NULL.
View 5 Replies
View Related