Showing posts with label stored. Show all posts
Showing posts with label stored. Show all posts

Friday, March 30, 2012

Problems installing External Stored procedure

Hi There

I'm having problems installing a external stored procedure that I created in Visual C++. I've created the .ddl and put it in the correct directory.

I've run the following commands to install it
sp_addextendedproc xp_regex, "D:\garth\ExternalStoredProcedures\Tecas\xp_regex.dll"

I then exec the procedure and get the following:

execute master..xp_regex

ODBC: Msg 0, Level 16, State 1
Cannot load the DLL \\tedevsql02\garth\ExternalStoredProcedures\Tecas, or one of the DLLs it references. Reason: 126(The specified module could not be found.).

The .dll is definately in that directory. I'm not sure what I'm doing wrong. Any tips?

Thanks

SynAck
Sorry, that error should read as follows:

ODBC: Msg 0, Level 16, State 1
Cannot load the DLL D:\garth\ExternalStoredProcedures\Tecas\xp_regex.dll, or one of the DLLs it references. Reason: 126(The specified module could not be found.).

|||

Make sure you have also copied to that directory other .dll's that you reference from you program.

|||At the moment, the program is the equivilent of a "hello world" program

Wednesday, March 28, 2012

Problems inserting datetime object into sql server 2005

hey everyone,

Im trying run a stored procedure, but I am getting the following message when trying to execute it.

Implicit conversion from data type datetime to int is not allowed. Use the CONVERT function to run this query.

which seems strange, as there is no integer going to a datetime field. Also, it does not return the value that is incorrect, nor the parameter that is failing. If there is anyway to view this in VS 2005 Team suite, please let me know.

It should also be noted that when I execute this sproc from within sql management studio, it executes fine.

This is the stored procedure im trying to execute...

CREATE PROCEDURE [dbo].[sp_UpdateRequest]

@.request_id INT,
@.request_client_id INT,
@.request_description VARCHAR(150), @.request_date DATETIME,
@.request_edit_date DATETIME, @.request_status VARCHAR(25), @.request_approve_date DATETIME,
@.request_activity_code VARCHAR(7), @.request_department_code VARCHAR(3), @.request_participants INT,
@.request_activity_date DATETIME, @.request_activity_due_date DATETIME,
@.request_company_id INT, @.request_company_code INT,
@.request_notes VARCHAR(2000)

AS
BEGIN

UPDATE invoice_requests

SET request_client_id = @.request_client_id, request_description = @.request_description,
request_date = @.request_date, request_edit_date = @.request_edit_date,
request_status = @.request_status, request_approve_date = @.request_approve_date,
request_activity_code = @.request_activity_code,
request_department_code = @.request_department_code,
request_participants = @.request_participants,
request_activity_date = @.request_activity_date,
request_activity_due_date = @.request_activity_due_date,
request_company_code = @.request_company_code, request_company_id = @.request_company_id,
request_notes = @.request_notes

WHERE request_id = @.request_id

END
GO

in my .net app, all the datetime objects are valid dates, so I could not see why this would be generating the error that it is, so I ran the SQL Profiler, and this was the output. Again, i cannot see where im going wrong...

please note, I have seperated the output from the single slab of text, making sure I didnt remove anything...

exec sp_executesql
N'EXECUTE sp_UpdateRequest
@.request_id,
@.request_client_id,
@.request_description,
@.request_date,
@.request_edit_date,
@.request_status,
@.request_approve_date,
@.request_activity_code,
@.request_participants,
@.request_activity_date,
@.request_activity_due_date,
@.request_company_id,
@.request_company_code,
@.request_notes',

N'@.request_id int,
@.request_client_id int,
@.request_description varchar(8000),
@.request_date datetime,
@.request_edit_date datetime,
@.request_status varchar(5),
@.request_approve_date datetime,
@.request_activity_code varchar(8000),
@.request_department_code varchar(8000),
@.request_participants int,
@.request_activity_date datetime,
@.request_activity_due_date datetime,
@.request_company_id int,
@.request_company_code int,
@.request_notes varchar(8000)',

@.request_id=5,
@.request_client_id=1,
@.request_description='',
@.request_date=''2007-11-22 16:34:32:997'',
@.request_edit_date=''2007-11-22 16:34:32:997'',
@.request_status='Draft',
@.request_approve_date=''1970-01-01 00:00:00:000'',
@.request_activity_code='',
@.request_department_code='',
@.request_participants=0,
@.request_activity_date=''2007-11-29 00:00:00:000'',
@.request_activity_due_date=''2007-11-23 00:00:00:000'',
@.request_company_id=0,
@.request_company_code=1,
@.request_notes=''

any help on this would be greatly appreciated.
Cheershey everyone, when i try to run the the following trace result as a query, i get an error near 2007...

exec sp_executesql N'EXECUTE sp_UpdateRequest @.request_id, @.request_client_id, @.request_description, @.request_date, @.request_edit_date, @.request_status, @.request_approve_date, @.request_activity_code, @.request_participants,
@.request_activity_date, @.request_activity_due_date, @.request_company_id, @.request_company_code, @.request_notes',N'@.request_id int,@.request_client_id int,@.request_description varchar(6),@.request_date datetime,@.request_edit_date
datetime,@.request_status varchar(5),@.request_approve_date datetime,@.request_activity_code varchar(4),@.request_department_code varchar(3),@.request_participants int,@.request_activity_date datetime,@.request_activity_due_date
datetime,@.request_company_id int,@.request_company_code int,@.request_notes varchar(11)',@.request_id=1,@.request_client_id=1,@.r equest_description='Justin',@.request_date=''2007-11-23 08:59:04:250'',@.request_edit_date=''2007-11-23
08:59:04:250'',@.request_status='Draft',@.request_ap prove_date=''1970-01-01 00:00:00:000'',@.request_activity_code='0000',@.requ est_department_code='022',@.request_participants=50 ,@.request_activity_date=''2007-11-23
00:00:00:000'',@.request_activity_due_date=''2007-11-30 00:00:00:000'',@.request_company_id=5292,@.request_c ompany_code=1,@.request_notes='Other Notes'

are there meant to be the double single quotes('') before and after the date?

Cheers,|||are there meant to be the double single quotes('') before and after the date?No, there should be a single apostrophe surrounding (before and after) date constants.

Your constant ''2007-11-23 08:59:04:250'' syntactically ought to be '2007-11-23 08:59:04:250' for use in Microsoft SQL Server.

-PatP|||No, there should be a single apostrophe surrounding (before and after) date constants.

Your constant ''2007-11-23 08:59:04:250'' syntactically ought to be '2007-11-23 08:59:04:250' for use in Microsoft SQL Server.

-PatP

I'm not sure because it's already surrounded by single quotes.

maybe you can try '''2007-11-23 08:59:04:250'''|||Sorry, I should have looked at your whole example.

There are multiple ways that I could parse what you've posted. The one that makes the most sense to me at the moment is:exec sp_executesql N'EXECUTE sp_UpdateRequest
@.request_id, @.request_client_id, @.request_description
, @.request_date, @.request_edit_date, @.request_status
, @.request_approve_date, @.request_activity_code, @.request_participants
, @.request_activity_date, @.request_activity_due_date, @.request_company_id
, @.request_company_code, @.request_notes'', N''@.request_id int
, @.request_client_id int, @.request_description varchar(6), @.request_date datetime
, @.request_edit_date datetime, @.request_status varchar(5), @.request_approve_date datetime
, @.request_activity_code varchar(4), @.request_department_code varchar(3), @.request_participants int
, @.request_activity_date datetime, @.request_activity_due_date datetime, @.request_company_id int
, @.request_company_code int, @.request_notes varchar(11)''
, @.request_id = 1, @.request_client_id = 1, @.request_description = ''Justin''
, @.request_date = ''2007-11-23 08:59:04:250'', @.request_edit_date = ''2007-11-23 08:59:04:250''
, @.request_status = ''Draft'', @.request_approve_date = ''1970-01-01 00:00:00:000''
, @.request_activity_code = ''0000'', @.request_department_code = ''022'', @.request_participants = 50
, @.request_activity_date = ''2007-11-23 00:00:00:000'', @.request_activity_due_date = ''2007-11-30 00:00:00:000''
, @.request_company_id = 5292, @.request_company_code = 1, @.request_notes = ''Other Notes''
'See if that represents what you think you meant, and let me know how it works for you.

-PatPsql

Problems in executing SQL or Stored Procs with ASP

Hi experts,

I m working with MS SQL Server 2000 with ASP for my application. There're some Stored Procedures created for the new functions but seems I can't run these new SPs with my ASP pages. When I load that ASP page, it shows error message that can't find my SP. I've execute the SP alone in SQL Enterprise Manager and it works.

When I work with the SPs, I can connect with the DB with Enterprise Manager only without administrator right. As my SPs I suppose they should work with ASP but I just worry would it be the problem with my right granted in SQL server?

There are some other SPs running fine created by dbo but for my SPs not by dbo. Would there be any differences? Does it mean my SPs need to be granted by dbo instead of my current role? I m sure if I use the same ASP page then running another existing SPs, it works really smooth.

I also tried to make a SQL statement in my ASP page (e.g. an insert statement) but it seems nothing can be inserted. I got really screwed up!!!

Thanks in advance!!
Manfred

Manfred:

First, how are your ASP pages connecting to your database? Do you know they login, etc.? How do you give this login/user permissions to execute your stored procedure? Also, you might have an "owner" problem with the stored procedure object. Try running this query and posting the results:

select type,
uid,
left ([name], 40) as [name]
from sysobjects
where type = 'P'
and name = 'yourProcName'

-- - Sample Query Results: --

-- type uid name
-- - -
-- P 1 myProcName


Dave

|||

Thanks a lot for your advice Dave!

I got a dbo login name/password from my colleague and I've created a new SP under dbo login. It works! I can execute the stuff I want with the SP.

Here 's the query result

SELECT type, uid, LEFT(name, 40) AS name
FROM dbo.sysobjects
WHERE (type = 'P') AND (name = 'PROC_TESTDEPT')

-- type uid name
-- - -
-- P 1 proc_TestDept

Problems having moved from SQL 7 to SQL 2000

We ported our database 2 weeks ago. We have come across a problem with
one
stored procedure.
1) Running some queries / Procedures in Query Analyser return
"[Microsoft][ODBC SQL Server Driver][Shared
Memory]ConnectionCheckForData (CheckforData()).
Server: Msg 11, Level 16, State 1, Line 0
General network error. Check your network documentation.
Connection Broken"
The SQL Logs have the following errors whenever the procedure runs
* Exception Address = 00000000
* Exception Code = c0000005 EXCEPTION_ACCESS_VIOLATION
* Access Violation occurred reading address 00000000
I have tried to run the procedure from SQL Analyser on my client
machine and locally on the server. Both return the same error.
The stored procedure completes and the records appear in the relvent
tables. At best we get the errors described above and entries in teh
SQL log. The worst scenario we have had is each time the procedure
fired the AQL server services terminated unexpectedly disconencting
everyone from the SQL server and all databases (More of a problem I am
sure you will agree).
The stored procedure is outlined below. Running in SQL Analyser does
not display the printed debug messages although they are viewable in
the Stack dump.
SQL VERSION : Microsoft SQL Server 2000 - 8.00.760 (Intel X86) Dec
17 2002 14:22:05 Copyright (c) 1988-2003 Microsoft Corporation
Standard Edition on Windows NT 5.0 (Build 2195: Service Pack 4)
CREATE PROCEDURE spSaveNewCall
/*----*/
/* PROCEDURE : spSaveNewCall */
/* Description : saves a new call in database */
/*----*/
@.i_str_CustID varchar(50),
@.i_str_CustRef varchar(10),
@.i_str_ContactID int,
@.i_str_ProductCode varchar(6),
@.i_str_ModuleCode varchar(6),
@.i_str_Version varchar(10),
@.i_str_PatchLevel varchar(10),
@.i_str_EmergencyPatch varchar(10),
@.i_str_Environment varchar(4),
@.i_str_CallType varchar(100),
@.i_str_CallDescription text,
@.i_str_Priority varchar(1),
@.i_str_SLAclass varchar(10),
@.i_str_CustType varchar(15),
@.i_str_ModuleName varchar(40),
@.i_str_ProductName varchar(40),
@.i_str_ServerPlatform varchar(40)
AS
DECLARE @.l_str_CallID varchar(8)
DECLARE @.l_boo_calllog int
DECLARE @.l_boo_asgnmnt int
DECLARE @.l_boo_detail int
DECLARE @.l_boo_subset int
BEGIN TRANSACTION
print 'DEBUG : --update sequence number for anyone else trying to log
a call'
UPDATE HeatSeq
SET SeqValue = SeqValue + 1
WHERE SeqKey = 'CallID'
--get the next call id
SET @.l_str_CallID = (SELECT SeqValue AS NextCall FROM HEATSeq WHERE
SeqKey = 'CallID')
SET @.l_str_CallID = RIGHT('00000000' + @.l_str_CallID,8)
print 'DEBUG : --start logging call'
SET @.l_boo_calllog = 0
SET @.l_boo_asgnmnt = 0
SET @.l_boo_detail = 0
SET @.l_boo_subset = 0
INSERT INTO CallLog
( CallID,
CompanyRef,
CustID,
CallType,
CallStatus,
Tracker,
Priority,
CallDesc,
RecvdBy,
RecvdDate,
RecvdTime,
ModBy,
ModDate,
ModTime,
CallSource,
SLAClass,
Environment,
ProductCode,
ModuleCode,
OnHold,
ProductVersion,
PatchLevel,
EmergencyPatch,
CustType,
ProductModule,
Product,
DBPlatform,
SLA_ClockStatus,
SLA_CalcCBWarn,
SLA_CalcCloseWarn,
SLA_CalcClose,
SLA_CalcCB,
SLA_Status,
Weighting,
PriorityDesc,
ServerPlatform,
DTLastMod,
Escalated,
EscalationOrder
)
( SELECT @.l_str_CallID,
@.i_str_CustRef,
@.i_str_CustID,
@.i_str_CallType,
'Open',
'HSS',
@.i_str_Priority,
@.i_str_CallDescription,
'HSS',
CONVERT(varchar(10),GETDATE(),120),
CONVERT(varchar(8),GETDATE(),108),
'HSS',
CONVERT(varchar(10),GETDATE(),120),
CONVERT(varchar(8),GETDATE(),108),
'Website',
@.i_str_SLAclass,
@.i_str_Environment,
@.i_str_ProductCode,
@.i_str_ModuleCode,
'F',
@.i_str_Version,
@.i_str_PatchLevel,
@.i_str_EmergencyPatch,
@.i_str_CustType,
@.i_str_ModuleName,
@.i_str_ProductName,
'Progress',
'SLA is Stopped',
SLA_WarnResponse,
SLA_WarnComplete,
SLA_TgtComplete,
SLA_TgtResponse,
'OK',
Weighting,
SLA_PriorityDesc,
@.i_str_ServerPlatform,
datediff(ss,'01-01-1970',getdate()),
'F',
0
FROM SLAMatrix,
Priority
WHERE SLA_Priority = Priority.Priority
AND SLA_Priority = @.i_str_Priority
AND SLA_Class = @.i_str_SLAclass
)
print 'DEBUG : --check calllog has been updated'
SET @.l_boo_calllog = @.@.ERROR
print 'DEBUG : --save the subset'
INSERT INTO Subset
( CustID,
CallID,
CustType,
EmailID,
Phone,
CompanyName,
Contact,
Ext,
CustRefReq,
OrchMgr,
Phone2,
Ext2,
PhoneDesc1,
PhoneDesc2,
ContactMethod,
Fax1,
Alert,
AccMgr,
ProjMgr,
Supported,
Mobile,
KeyCustomer,
ContactSeqNum
)
( SELECT @.i_str_CustID,
@.l_str_CallID,
CustType,
Email1,
Telephone1,
CustomerName,
ContactName,
Extension1,
CustRef,
FPOC,
Telephone2,
Extension2,
Tel1Description,
Tel2Description,
ContactMethod,
Fax1,
ALERT,
AccountManager,
ProjectManager,
Supported,
Mobile1,
KeyCustomer,
ContactSeqNum
FROM Contacts, Profile
WHERE ContactSeqNum = @.i_str_ContactID
AND Contacts.CustID = Profile.CustID
)
print 'DEBUG : --check subset has been updated'
SET @.l_boo_subset = @.@.ERROR
print 'DEBUG : --save the details'
INSERT INTO Detail
(
CallID,
Details
)
VALUES
(
@.l_str_CallID,
''
)
print 'DEBUG : --check detail has been updated'
SET @.l_boo_detail = @.@.ERROR
print 'DEBUG : --save the assignment'
INSERT INTO Asgnmnt
(
AssignedBy,
DateAssign,
TimeAssign,
GroupName,
CallID,
HEATSeq,
GroupEMail,
DTLastMod,
Assignee,
GroupDesc,
ResolveOrder,
WhoResolv
)
VALUES
(
'HSS',
CONVERT(varchar(10),GETDATE(),120),
CONVERT(varchar(8),GETDATE(),108),
'WebUpdate',
@.l_str_CallID,
datediff(ss,'01-01-1970',getdate()),
'CustomerServices@.orchard-systems.co.uk',
datediff(ss,'01-01-1970',getdate()),
'HSS',
'New call logged on-line',
0,
''
)
print 'DEBUG : --check asgnmnt has been updated'
SET @.l_boo_asgnmnt = @.@.ERROR
IF @.l_boo_calllog = 0 AND @.l_boo_asgnmnt = 0 AND @.l_boo_detail = 0
AND @.l_boo_subset = 0
BEGIN
print 'DEBUG : --Transaction Commit'
COMMIT TRANSACTION
--return the call id
SELECT @.l_str_CallID AS NextCall
END
ELSE
BEGIN
print 'DEBUG : --Transaction Rollback'
ROLLBACK TRANSACTION
SELECT 'No Call Raised' AS NextCall
END
/*----*/
GOAt the very least, you need to correct your logic to accurately figure out
what is happening. You have a fundamental mistake in your error handling.
Try the following:
if object_id ('tempdb..#test') is not null
drop table #test
create table #test (test_id int not null)
insert #test (test_id) values (null)
print 'debug'
select @.@.error
insert #test (test_id) values (null)
select @.@.error
print 'debug'
go
Notice how the print statement changes the value of @.@.error. Erland has an
excellent discussion of error handling
(http://www.sommarskog.se/error-handling-II.html). Once you understand the
above, you should then correct the 2nd logic error. There would appear to
be no need to execute any insert statements that follow the first failed
insert statement. Yet your procedure just keeps blindly inserting until the
end. This only wastes server resources. You should also review any trigger
logic that will execute - this is a frequent problem area.
Inspite of the logic issues, the error log indicates that the fault is
within sql server. This requires assistance from MS to diagnose and
correct. The profiler might offer some insight - perhaps there is a problem
with parallelism. If so, you might be able to at least avoid the problem.
Perhaps the problem can be avoided entirely by correcting the logic flaws
alone.

Monday, March 26, 2012

Problems getting all the data back with a XML query

I am having a nightmare trying to get to the bottom of this problem.
I have a stored procedure that has a user defined function to create a
select table from a csv string of IDs.
The function and the Stored procedure works fine and returns the XML,
Elements as required except that when i process this sp on the client most
of the data is missing.
If i run the query in the query analyser with the csv parameter and no FOR
XML output i get 72 records (10 unique resources, the rest are due to the
joins in the query)
If i run it with the FOR XML i get 6 lines of XML although it is oddly
truncated. If i cut and past it into xmlspy there are missing elements so i
can't verify exactly what i'm getting.
But when i run this in my web app and use am XMLTextReader to turn the
results into a string I get 2 records, when i was expecting 10. I can verify
this by pasting the xml into xmlspy.
I have tried SQLXML managed classes but can't get them to accept parameters,
i keep getting the message that the sp is expecting parameter despite using
createParameter against the command as per all the documentation, so i gave
up with this approach. I thought that this way i could populate a new
dataset and then bind a table to a datagrid control to see what was
returned. I can get it all to work bar the parameters.
Can anyone shed any light on why the results are significantly less than the
sp should return
and can someone give me an example of working with a parameterised sp and
SQLXML
Many thanks
John
VS2003, SQLXML sp2, XPpro sp2
I am confused about what you are trying to get.
FOR XML results a single XML stream if you use the supported APIs through
ADO.Net, ADO, or OLEDB's stream interfaces. Query Analyser is using ODBC and
thus shows the XML result junked into 2033 characters per row. You should
not use QA if you plan on further process the result.
So if you can provide us with some more information about what exactly you
do on the API level, we may be able to help...
Best regards
Michael
"John Mas" <mase@.btopenworld.org> wrote in message
news:G2x8d.316$Xy3.217@.newsfe6-gui.ntli.net...
>I am having a nightmare trying to get to the bottom of this problem.
> I have a stored procedure that has a user defined function to create a
> select table from a csv string of IDs.
> The function and the Stored procedure works fine and returns the XML,
> Elements as required except that when i process this sp on the client most
> of the data is missing.
> If i run the query in the query analyser with the csv parameter and no FOR
> XML output i get 72 records (10 unique resources, the rest are due to the
> joins in the query)
> If i run it with the FOR XML i get 6 lines of XML although it is oddly
> truncated. If i cut and past it into xmlspy there are missing elements so
> i can't verify exactly what i'm getting.
> But when i run this in my web app and use am XMLTextReader to turn the
> results into a string I get 2 records, when i was expecting 10. I can
> verify this by pasting the xml into xmlspy.
> I have tried SQLXML managed classes but can't get them to accept
> parameters, i keep getting the message that the sp is expecting parameter
> despite using createParameter against the command as per all the
> documentation, so i gave up with this approach. I thought that this way i
> could populate a new dataset and then bind a table to a datagrid control
> to see what was returned. I can get it all to work bar the parameters.
> Can anyone shed any light on why the results are significantly less than
> the sp should return
> and can someone give me an example of working with a parameterised sp and
> SQLXML
>
> Many thanks
> John
> VS2003, SQLXML sp2, XPpro sp2
>
|||Xref: TK2MSFTNGP08.phx.gbl microsoft.public.sqlserver.xml:25072
Michael,
thanks I have sorted the problem eventually. Brain fade and not enough time
thinking it throgh. The problem was in the sql statement which took ages to
track down but there we go.
One question that is unanswered is how do i pass parameters to SQLXML with
stored procedures, not raw sql text?
i keep getting the message expecting parameter as per my post
thanks
john
"Michael Rys [MSFT]" <mrys@.online.microsoft.com> wrote in message
news:Ok7uv9DrEHA.2796@.TK2MSFTNGP10.phx.gbl...
>I am confused about what you are trying to get.
> FOR XML results a single XML stream if you use the supported APIs through
> ADO.Net, ADO, or OLEDB's stream interfaces. Query Analyser is using ODBC
> and thus shows the XML result junked into 2033 characters per row. You
> should not use QA if you plan on further process the result.
> So if you can provide us with some more information about what exactly you
> do on the API level, we may be able to help...
> Best regards
> Michael
> "John Mas" <mase@.btopenworld.org> wrote in message
> news:G2x8d.316$Xy3.217@.newsfe6-gui.ntli.net...
>
|||To what exactly do you want to pass parameters? SQLXML is a general term and
the name of the mid-tier component.
Do you mean how to pass parameters into the SQL statement that uses FOR XML
via stored procs?
Thanks
Michael
"John Mas" <mase@.btopenworld.org> wrote in message
news:Fmz9d.270$Vd.96@.newsfe5-win.ntli.net...
> Michael,
> thanks I have sorted the problem eventually. Brain fade and not enough
> time thinking it throgh. The problem was in the sql statement which took
> ages to track down but there we go.
> One question that is unanswered is how do i pass parameters to SQLXML with
> stored procedures, not raw sql text?
> i keep getting the message expecting parameter as per my post
> thanks
> john
>
> "Michael Rys [MSFT]" <mrys@.online.microsoft.com> wrote in message
> news:Ok7uv9DrEHA.2796@.TK2MSFTNGP10.phx.gbl...
>
|||Michael
here is the code that i am using
Dim strConn = "provider=SQLOLEDB;data source='....';initial
catalog=......;user id=sa;password=......"
Dim sxcCmd As New SqlXmlCommand(strConn)
Dim sdaDA As New SqlXmlAdapter(sxcCmd)
Dim sxpParam As SqlXmlParameter
Dim xr As Xml.XmlReader
Dim ds As New DataSet
With sxcCmd
..RootTag = "root"
..CommandType = SqlXmlCommandType.Sql
..CommandText = "Test2"
sxpParam = .CreateParameter
End With
With sxpParam
..Name = "@.IDs"
..Value = 5
End With
sdaDA.Fill(ds)
DataGrid1.DataSource = ds.Tables(0)
and here is the sp
ALTER PROCEDURE dbo.test2
(
@.IDs int
)
AS
/* SET NOCOUNT ON */
SELECT '<root>'
SELECT * FROM tblResource WHERE ResourceID=@.Ids
FOR XML AUTO, Elements
SELECT '</root>'
as you can see the sp has this parameter @.IDs but when i run the code the
error meesage says ' expecting parameter @.IDs'' yet i am passing it. If i
change the command text to a sql statement with a ? for the parameter then
it works.
Obviously i am missing something here, I presume the command type might be
wrongly set.
thanks
john
"Michael Rys [MSFT]" <mrys@.online.microsoft.com> wrote in message
news:O45cbdZrEHA.1964@.TK2MSFTNGP12.phx.gbl...
> To what exactly do you want to pass parameters? SQLXML is a general term
> and the name of the mid-tier component.
> Do you mean how to pass parameters into the SQL statement that uses FOR
> XML via stored procs?
> Thanks
> Michael
> "John Mas" <mase@.btopenworld.org> wrote in message
> news:Fmz9d.270$Vd.96@.newsfe5-win.ntli.net...
>

Problems Executing Stored procedure OLEDB

<sigh> been doing all kinds of stuff in SSIS and then I get to what I thought should be simple: Running a stored procedure, and I've had nothing but headache:

OLEDB connection, ResultSet None

SQL Statement: EXEC dbo.pStoredProcedure ?, ?, ?, ?, ?, ?, ? OUTPUT

Parameters Mapping page:

User::gvSourceName Input VARCHAR 0, User::gvDestinationName Input VARCHAR 1, System::UserName Input VARCHAR 2 etc.. etc.. UserlvDataImportID Output NUMERIC 6

I've emptied my stored procedure out... but that doesn't seem to matter it doesn't ever run the procedure. If I try to parse the Query I get the error "The Query failed to parse. Attempted to read or write protected memory. This is often an indication that other memory is corrupt."

If I run the package I get the error: [Execute SQL Task] Error: Executing the query "EXEC dbo.pStoredProcedure ?, ?, ?, ?, ?, ?, ? OUTPUT" failed with the following error: "Unspecified error". Possible failure reasons: Problems with the query, "ResultSet" property not set correctly, parameters not set correctly, or connection not established correctly.

I've tried without the output variable and I still get the corrupt memory error and when I run the package I get: [Execute SQL Task] Error: Executing the query "EXEC dbo.pDataImportInfoInitINSERT ?, ?, ?, ?, ?, ?" failed with the following error: "Invalid character value for cast specification". Possible failure reasons: Problems with the query, "ResultSet" property not set correctly, parameters not set correctly, or connection not established correctly.

Even though I have made sure the datatypes match exactly between the parameters in the stored procedure and in the execute sql. I also know my connection is good as I use it in many steps before I get to the execute sql task...

Any ideas? I've tried just about everything I can think of short of building a whole new package...

FYI I can get it to working using the ADO.NET method (spelling out the parameter names etc) so long as I set the "IsQueryStoredProcedure" to false... I don't know why the oledb method is giving me so many problems - I'd like to keep only one connection to the database so having an OLE DB connection for everything except my execute sql tasks is only an option if there is no other way....|||I don't know what the deal was... I deleted the object and rebuilt it and now it is working including the output parameter.. except it doesn't like the date parameters I pass it... is there any way to actually see what the SSIS is passing to SQL? In the logs it just shows all ? marks.|||

Good news to those having similar problems (if anyone)... I found the problem:

I was using NUMERIC for the return type (in SQL the return was an INT) in my original object that had all the issues. In the new one I used LONG as the return.

IMHO this is the biggest pain with SSIS - the datatyping (and the lack of errors to tell you datatyping is the issue when it fails). Now I know why they did it etc (so you know every explicit conversion for tuning purposes) - which I understand and agree with but the different objects have different choices is what is so tough for me... ie the parameters datatypes didn't have INT or INT16/32 etc... and the datatypes you can choose for your variables are another set etc... In the DB world I generally use Varchar, int, and smalldatetimes and what datatype to map that to in SSIS seems to be a mystery that depends on what object you are dealing with..

Any chance Microsoft can at the very least issue a whitepaper on tips for datatypes when dealing with SSIS and SQL server?

|||

Chris Honcoop wrote:

Good news to those having similar problems (if anyone)... I found the problem:

I was using NUMERIC for the return type (in SQL the return was an INT) in my original object that had all the issues. In the new one I used LONG as the return.

could you not map the parameter to an ssis variable? afaik, this is the preferred way in ssis to execute stored procedures.

|||The parameter was mapped as an output parameter (that is what I meant by "return type" sorry that is not very clear). In the SQL the output parameter was INT... in SSIS my variable mapping was NUMERIC... which caused errors while LONG worked great.|||

Hi,

I too have similar problem but the error what i am getting now is

[Execute SQL Task] Error: Executing the query "exec spm_Utopia_FinanceUsage_Create_MonthlyTable ?,? OUTPUT " failed with the following error: "Multiple-step OLE DB operation generated errors. Check each OLE DB status value, if available. No work was done.". Possible failure reasons: Problems with the query, "ResultSet" property not set correctly, parameters not set correctly, or connection not established correctly.

The parametrs used are user:tableName input varchar 0,user:filegroupName input varchar 1,user:return_value output Long 2

sp returns a integer value so i am using long.

I tried using returnvalue instead of output still no use.

I tried the ADO.net connection it works fine but since i am using oledb connection i want to keep it through out.

|||Hmmm I have not seen that error. How are you "returning" the value - with a output variable or just returning it from the sproc?. That determines if you use the ? OUTPUT (if you return it via variable) or result set (for example if you select/print etc the result in the sp)sql

Problems Executing Stored procedure OLEDB

<sigh> been doing all kinds of stuff in SSIS and then I get to what I thought should be simple: Running a stored procedure, and I've had nothing but headache:

OLEDB connection, ResultSet None

SQL Statement: EXEC dbo.pStoredProcedure ?, ?, ?, ?, ?, ?, ? OUTPUT

Parameters Mapping page:

User::gvSourceName Input VARCHAR 0, User::gvDestinationName Input VARCHAR 1, System::UserName Input VARCHAR 2 etc.. etc.. UserlvDataImportID Output NUMERIC 6

I've emptied my stored procedure out... but that doesn't seem to matter it doesn't ever run the procedure. If I try to parse the Query I get the error "The Query failed to parse. Attempted to read or write protected memory. This is often an indication that other memory is corrupt."

If I run the package I get the error: [Execute SQL Task] Error: Executing the query "EXEC dbo.pStoredProcedure ?, ?, ?, ?, ?, ?, ? OUTPUT" failed with the following error: "Unspecified error". Possible failure reasons: Problems with the query, "ResultSet" property not set correctly, parameters not set correctly, or connection not established correctly.

I've tried without the output variable and I still get the corrupt memory error and when I run the package I get: [Execute SQL Task] Error: Executing the query "EXEC dbo.pDataImportInfoInitINSERT ?, ?, ?, ?, ?, ?" failed with the following error: "Invalid character value for cast specification". Possible failure reasons: Problems with the query, "ResultSet" property not set correctly, parameters not set correctly, or connection not established correctly.

Even though I have made sure the datatypes match exactly between the parameters in the stored procedure and in the execute sql. I also know my connection is good as I use it in many steps before I get to the execute sql task...

Any ideas? I've tried just about everything I can think of short of building a whole new package...

FYI I can get it to working using the ADO.NET method (spelling out the parameter names etc) so long as I set the "IsQueryStoredProcedure" to false... I don't know why the oledb method is giving me so many problems - I'd like to keep only one connection to the database so having an OLE DB connection for everything except my execute sql tasks is only an option if there is no other way....|||I don't know what the deal was... I deleted the object and rebuilt it and now it is working including the output parameter.. except it doesn't like the date parameters I pass it... is there any way to actually see what the SSIS is passing to SQL? In the logs it just shows all ? marks.|||

Good news to those having similar problems (if anyone)... I found the problem:

I was using NUMERIC for the return type (in SQL the return was an INT) in my original object that had all the issues. In the new one I used LONG as the return.

IMHO this is the biggest pain with SSIS - the datatyping (and the lack of errors to tell you datatyping is the issue when it fails). Now I know why they did it etc (so you know every explicit conversion for tuning purposes) - which I understand and agree with but the different objects have different choices is what is so tough for me... ie the parameters datatypes didn't have INT or INT16/32 etc... and the datatypes you can choose for your variables are another set etc... In the DB world I generally use Varchar, int, and smalldatetimes and what datatype to map that to in SSIS seems to be a mystery that depends on what object you are dealing with..

Any chance Microsoft can at the very least issue a whitepaper on tips for datatypes when dealing with SSIS and SQL server?

|||

Chris Honcoop wrote:

Good news to those having similar problems (if anyone)... I found the problem:

I was using NUMERIC for the return type (in SQL the return was an INT) in my original object that had all the issues. In the new one I used LONG as the return.

could you not map the parameter to an ssis variable? afaik, this is the preferred way in ssis to execute stored procedures.

|||The parameter was mapped as an output parameter (that is what I meant by "return type" sorry that is not very clear). In the SQL the output parameter was INT... in SSIS my variable mapping was NUMERIC... which caused errors while LONG worked great.|||

Hi,

I too have similar problem but the error what i am getting now is

[Execute SQL Task] Error: Executing the query "exec spm_Utopia_FinanceUsage_Create_MonthlyTable ?,? OUTPUT " failed with the following error: "Multiple-step OLE DB operation generated errors. Check each OLE DB status value, if available. No work was done.". Possible failure reasons: Problems with the query, "ResultSet" property not set correctly, parameters not set correctly, or connection not established correctly.

The parametrs used are user:tableName input varchar 0,user:filegroupName input varchar 1,user:return_value output Long 2

sp returns a integer value so i am using long.

I tried using returnvalue instead of output still no use.

I tried the ADO.net connection it works fine but since i am using oledb connection i want to keep it through out.

|||Hmmm I have not seen that error. How are you "returning" the value - with a output variable or just returning it from the sproc?. That determines if you use the ? OUTPUT (if you return it via variable) or result set (for example if you select/print etc the result in the sp)

Problems executing Database Engine Tuning Advisor

We are trying to optimize one of our databases (SQL 2005) and we are running analysis on some of the stored procedures. However, the Database Engine Tuning Advisor is resulting in either

Event does not reference any tables.

Or

Statement does not reference any tables.

Anyone have any idea why this would happen?

PLease explain the process how you are trying analyze the SP using DTA?

ALso may try from another machine to see whether its a problem of tools on this machine.

|||Thanks for replying. Sorry I lost track of the thread. Essentially, all we are doing is executing a stored procedure in a query window and analyzing that directly.

Also, if we log the execution and use the trace log to do the analysis we get the same.

It has been tried in multiple machines. It is weird since there's no errors with the stored procedures. Thanks again.|||I have the same problem, a lot of those errors, plus after a while (from 25 to 60 minutes) the DTA exits with an "unexpected error".|||this happens against any stored procedure that DTA analyzes, why?

Problems executing Database Engine Tuning Advisor

We are trying to optimize one of our databases (SQL 2005) and we are running analysis on some of the stored procedures. However, the Database Engine Tuning Advisor is resulting in either

Event does not reference any tables.

Or

Statement does not reference any tables.

Anyone have any idea why this would happen?

PLease explain the process how you are trying analyze the SP using DTA?

ALso may try from another machine to see whether its a problem of tools on this machine.

|||Thanks for replying. Sorry I lost track of the thread. Essentially, all we are doing is executing a stored procedure in a query window and analyzing that directly.

Also, if we log the execution and use the trace log to do the analysis we get the same.

It has been tried in multiple machines. It is weird since there's no errors with the stored procedures. Thanks again.|||I have the same problem, a lot of those errors, plus after a while (from 25 to 60 minutes) the DTA exits with an "unexpected error".|||this happens against any stored procedure that DTA analyzes, why?

Problems executing Database Engine Tuning Advisor

We are trying to optimize one of our databases (SQL 2005) and we are running analysis on some of the stored procedures. However, the Database Engine Tuning Advisor is resulting in either

Event does not reference any tables.

Or

Statement does not reference any tables.

Anyone have any idea why this would happen?

PLease explain the process how you are trying analyze the SP using DTA?

ALso may try from another machine to see whether its a problem of tools on this machine.

|||Thanks for replying. Sorry I lost track of the thread. Essentially, all we are doing is executing a stored procedure in a query window and analyzing that directly.

Also, if we log the execution and use the trace log to do the analysis we get the same.

It has been tried in multiple machines. It is weird since there's no errors with the stored procedures. Thanks again.|||I have the same problem, a lot of those errors, plus after a while (from 25 to 60 minutes) the DTA exits with an "unexpected error".
|||this happens against any stored procedure that DTA analyzes, why?
sql

Friday, March 23, 2012

Problems creating Error File when using Bulk Insert or BCP from xp_cmdshell.

BCP thru xp_cmdshell from stored procedure:

EXEC sp_configure 'show advanced options', 1;

RECONFIGURE

EXEC sp_configure 'xp_cmdshell', 1;

RECONFIGURE

EXEC xp_cmdshell 'bcp database.dbo.table in c:\scheduled.csv -S SERVER\SQLEXPRESS -T -t, -r\n -c -e "error.txt"';

This is returning the following error code. I even tried placing the command in a seperate command file and calling that with no success. If I run this from the command line the error file generation does work.

=================================================================

SQLState = HY000, NativeError = 0

Error = [Microsoft][SQL Native Client]Unable to open BCP error-file

=================================================================

Error message when using BULK INSERT as follows:

BULK INSERT database.dbo.table from 'c:\unscheduled.csv' with

(FIELDTERMINATOR = ',', ERRORFILE = 'c:\error.txt');

Returns the following error message:

=================================================================

Msg 4861, Level 16, State 1, Procedure pro_cedure, Line 9

Cannot bulk load because the file "c:\error.txt" could not be opened. Operating system error code 80(The file exists.).

Msg 4861, Level 16, State 1, Procedure pro_cedure, Line 9

Cannot bulk load because the file "c:\error.txt.Error.Txt" could not be opened. Operating system error code 80(The file exists.).

=================================================================

The Bulk Insert actually creates a empty error.txt file (0kb) and never preforms the insert, I can not find any examples of anyone using the -ERRORFILE switch on BULK INSERT. Prolly some default security setting to allow file creation/modification I am missing. Anyone help me out? Thanks.

EDIT: SQL SERVER EXPRESS 2005 - WINXP PRO SP2

I had this error too. It looks like a bug as BULK INSERT works fine without the -ERRORFILE option. It seems that the execution of the BULK INSERT first creates the file without closing it which results in the error message afterwards. As Workaround just don't use the option

Nobsay

Problems creating a View

I have a query on one of my pages that is just too large to keep in the page, so I need to reference a stored view in sql. I'm kind of new to this, so I'm having trouble getting the syntax right. The query is just a simple select statement using the results of several textboxes as parameters. I know how to do the query inside an asp.net page, but when I move it to sql, I don't know how to reference the textbox value i.e. @.textbox. Here's what I have so far:
USE [Maindb]
GO
CREATE VIEW [tblMain_view] (@.textbox nvarchar(30)) ??
AS SELECT dbo.tblMain.Field1, ...
FROM dbo.tblMain
WHERE dbo.tblMain.Field1 = @.textbox and ...

First of all, I know that where I declare @.textbox is wrong, so where is the right place to declare it? Also, how do I reference the view from the webpage and do I still use:
cmd.SelectCommand.Parameters.Add . . .
in the page to establish the value. Anyone know a good tutorial on this. All the ones I've found were either in C# or didn't really apply. I need to know how to do this in VB. ThanksUSE [Maindb]
GO
CREATE VIEW [tblMain_view] (@.textbox nvarchar(30)) ??
AS SELECT dbo.tblMain.Field1, ...
FROM dbo.tblMain
WHERE dbo.tblMain.Field1 = @.textbox and ...

USE Your DB
IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.VIEWS
WHERE TABLE_NAME = 'Yourtable')
GO
CREATE VIEW Name
AS
SELECT col1,col2,
FROM your table
WHERE

Try the above statement with your info, your code is missing the WHERE clause before the create view. Run a search for create View in the BOL or use my email address in my profile and I will send you the VIEW tutorial I wrote a while back. Sorry cannot help you with VB I write C#. Hope this helps.

Kind regards,
Gift Peddiesql

Problems creating a stored procedure in Management Studio

Hi,

I am probably going to sound really stupid but I have recently installed SQL Server Management Studio and been trying to figure out how to create a stored procedure in it. I have created a database called 'BTL_Dictionary' and that works fine. In the Object Explorer window when I click on the database, I get the tree view of all the different options. In order to write the stored procedure , I clicked on Programmability --> Stored Procedures --> New Stored Procedure.

This opened up the template and i made the following changes to the template :

-- =============================================

SET ANSI_NULLS ON

GO

SET QUOTED_IDENTIFIER ON

GO

-- =============================================

-- Author: blah

-- Create date:

-- Description: Adds the values into the DictionaryTable

-- =============================================

CREATE PROCEDURE [dbo].[AddDictionary]

-- Add the parameters for the stored procedure here

@.DictionaryID int ,

@.DictionaryName nvarchar(50),

@.DictionaryType nvarchar(50)

AS

BEGIN

-- Insert statements for procedure here

INSERT INTO DictionaryTable

(

DictionaryID,

DictionaryName,

DictionaryType

)

VALUES

(

@.DictionaryID ,

@.DictionaryName ,

@.DictionaryType

)

END

GO

-- =============================================

I saved the stored procedure, but when I refresh the database, I cannot see the stored procedure there. I trired re-opening the query and it indicates that the procedure belongs to the 'master' database instead of the 'BTL_Dictionary' database (its prefixed 'master.AddDictionary' instead of ''BTL_Dictionary.AddDictionary')

Can anyone tell me whats is is that I am doing wrong and how I can get rid of this .

Thanks

When you click "New Stored Procedure" MS will open a new query window with the PROC template in it. Just check that the database context is set to your database and not the master database. Or add a "USE" statement before the first statement in the template to ensure that the context is correct.

|||Thanks a lot for , that resolved the problem.

Wednesday, March 21, 2012

Problems Connecting to Database

I am having a hard time getting my registration form to connect to my database via a stored procedure. Any help would be appreciated. The code is listed below

protectedvoid submit_Click(object sender,EventArgs e)

{

SqlConnection connection =

newSqlConnection(ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString);

SqlCommand command =

newSqlCommand("GE_sp_INSERT_USER", connection);

command.Parameters.Add("@.FirstName",SqlDbType.NVarChar).Value = txtFirstName.Text;

command.Parameters.Add("@.LastName",SqlDbType.NVarChar).Value = txtLastName.Text;

command.Parameters.Add("@.UserName",SqlDbType.NVarChar).Value = txtUserName.Text;

command.Parameters.Add("@.Password",SqlDbType.NVarChar).Value = txtPassword.Text;

command.Parameters.Add("@.PhoneNumber",SqlDbType.NVarChar).Value = txtPhoneNumber.Text;

command.Parameters.Add("@.EmailAddress",SqlDbType.NVarChar).Value = txtEmailAddress.Text;

command.Parameters.Add("@.Address",SqlDbType.NVarChar).Value = txtAddress.Text;

command.Parameters.Add("@.City",SqlDbType.NVarChar).Value = txtCity.Text;

command.Parameters.Add("@.State",SqlDbType.NVarChar).Value = txtState.Text;command.Parameters.Add("@.ZipCode",SqlDbType.NVarChar).Value = txtZipCode.Text;

connection.Open();

command.ExecuteNonQuery();

connection.Dispose();

}

ALTER PROCEDUREdbo.GE_sp_INSERT_USER

(

@.FirstNamenvarchar(50),

@.LastNamenvarchar(50),

@.UserNamenvarchar(50),

@.Passwordnvarchar(50),

@.PhoneNumbernvarchar(50),

@.EmailAddressnvarchar(50),

@.Addressnvarchar(50),

@.Citynvarchar(50),

@.Statenvarchar(50),@.ZipCodenvarchar(50)

)

AS

INSERT INTOUSERS

(FirstName, LastName, UserName, Password, PhoneNumber, EmailAddress, Address, City, State, ZipCode)

VALUES

(@.FirstName, @.LastName, @.UserName, @.Password, @.PhoneNumber, @.EmailAddress, @.Address, @.City, @.State, @.ZipCode)

RETURN

You say you are having a hard time "connecting" to your database. What exactly is the problem you're having? Are you getting an error?

|||

You need to set the CommandType:

command.CommandType =CommandType.StoredProcedure;

|||

I have added the code below to my code - I placed it right below my sqlCommand. - it still does not work. the error says it cannot find the stored procedure. The webconfig looks correct.

SqlCommand command =newSqlCommand("GE_sp_INSERT_USER", connection);

command.CommandType =CommandType.StoredProcedure;

thanks for your help|||

That error message has meaning.

Try this:

SqlCommand command =newSqlCommand("dbo.GE_sp_INSERT_USER", connection);

|||

That did not work either. Below is my webconfig - I may be missing something easy.

<connectionStrings>

<addname="myConnectionString"connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\gevjen.mdf;Integrated Security=True;User Instance=True"providerName="System.Data.SqlClient"/>

</connectionStrings>

thanks again for sticking with this to help me out...

|||

A few things

1) Is this connection string working somewhere else in your application?

2) If you connect to your db manually and execute the command do you get any result?

|||

hey i am too getting a hard time in making connection to sqlserver,like i have made a connection object and its working but when i reach the open function nothing works,i had been working over this since last 4 days!please guide me how to do it!

|||The database works elsewhere and the stored procedure works as well. I am missing something easy I believe within the connection or webconfig.|||

gevjen:

The database works elsewhere and the stored procedure works as well. I am missing something easy I believe within the connection or webconfig.

Could you copy and paste the actual error message, and the show the line that causes it?

|||

kamna:

hey i am too getting a hard time in making connection to sqlserver...

This should help you:http://www.mikesdotnetting.com/Article.aspx?ArticleID=69

sql

Problems catching @@error from trigger on insert from openxml

Have kind of an oddball scenario that needs a solution.
I have a stored proc which is passed XML that pulls out sections of the xml
for inserts into 3 different tables.
The first insert has an "instead of" trigger that on rare occasions raises
an error.
After that first insert (using an "insert into ... select * from openxml"
form) I need to know if that error was raised. Testing @.@.ERROR always gives
me 0.
Is this an issue with the openxml insert form?
What I would like to do is rollback a transaction if any of the inserts fail.Just put all the 3 inserts in a transaction with
BEGIN TRANSACTION
INSERT 1
IF @.@.TRANCOUNT > 0
INSERT 2
IF @.@.TRANCOUNT > 0
INSERT 3
IF @.@.TRANCOUNT > 0
COMMIT TRANSACTION
An error (any error) in a trigger will terminate and rollback the
transaction that fired it. The thing you want to avoid to do after that is
so the next inserts. The code above will give you some control over the
exact execution, but if you don't need that, you can use SET XACT_ABORT ON
before you start the transaction, and no code will be executed in the batch
after an error is encountered.
You probably don't see any value for @.@.ERROR because you don't check it
immediately after the statement that raises the error (easy mistake to
make).
For some more background information read these excellent articles by SQL
Server MVP Erland Sommarskog:
http://www.sommarskog.se/error-handling-I.html
http://www.sommarskog.se/error-handling-II.html
--
Jacco Schalkwijk
SQL Server MVP
"D.Kratt" <DKratt@.discussions.microsoft.com> wrote in message
news:7EFFB116-37E6-4188-8500-2846C5233AEA@.microsoft.com...
> Have kind of an oddball scenario that needs a solution.
> I have a stored proc which is passed XML that pulls out sections of the
> xml
> for inserts into 3 different tables.
> The first insert has an "instead of" trigger that on rare occasions raises
> an error.
> After that first insert (using an "insert into ... select * from openxml"
> form) I need to know if that error was raised. Testing @.@.ERROR always
> gives
> me 0.
> Is this an issue with the openxml insert form?
> What I would like to do is rollback a transaction if any of the inserts
> fail.|||Tried both (thanks for the suggestions, eventually got me to a solution),
but didn't work until I placed an explicit ROLLBACK TRANSACTION right before
my raiseerror in the insert trigger on the first table.
"Jacco Schalkwijk" wrote:
> Just put all the 3 inserts in a transaction with
> BEGIN TRANSACTION
> INSERT 1
> IF @.@.TRANCOUNT > 0
> INSERT 2
> IF @.@.TRANCOUNT > 0
> INSERT 3
> IF @.@.TRANCOUNT > 0
> COMMIT TRANSACTION
> An error (any error) in a trigger will terminate and rollback the
> transaction that fired it. The thing you want to avoid to do after that is
> so the next inserts. The code above will give you some control over the
> exact execution, but if you don't need that, you can use SET XACT_ABORT ON
> before you start the transaction, and no code will be executed in the batch
> after an error is encountered.
> You probably don't see any value for @.@.ERROR because you don't check it
> immediately after the statement that raises the error (easy mistake to
> make).
> For some more background information read these excellent articles by SQL
> Server MVP Erland Sommarskog:
> http://www.sommarskog.se/error-handling-I.html
> http://www.sommarskog.se/error-handling-II.html
> --
> Jacco Schalkwijk
> SQL Server MVP
>
> "D.Kratt" <DKratt@.discussions.microsoft.com> wrote in message
> news:7EFFB116-37E6-4188-8500-2846C5233AEA@.microsoft.com...
> > Have kind of an oddball scenario that needs a solution.
> >
> > I have a stored proc which is passed XML that pulls out sections of the
> > xml
> > for inserts into 3 different tables.
> >
> > The first insert has an "instead of" trigger that on rare occasions raises
> > an error.
> > After that first insert (using an "insert into ... select * from openxml"
> > form) I need to know if that error was raised. Testing @.@.ERROR always
> > gives
> > me 0.
> >
> > Is this an issue with the openxml insert form?
> >
> > What I would like to do is rollback a transaction if any of the inserts
> > fail.
>
>

Problems calling a stored procedures depending on parameters

Hi guys, hoping one of you may be able to help me out. I am using VS 2005, and VB.net for a Windows application.

I have a table in SQL that has a list of Storedprocedures: Sprocs Table: SPID - PK (int), ID (int), NAME (string), TYPE (string)
The ID is a Foreign key (corresponding to a Company ID), the name is the stored procedure name, and Type (is the type of SP).

On my application I need to a certain SP depending on the company selected and what page you are on. I have a seperate SP that passes in parameters for both Company, and Type and should output the Name value:

ALTERPROCEDURE [dbo].[S_SPROC]
(@.IDint,@.TYPECHAR(10),@.NAMECHAR(20) OUTPUT)
AS

SELECT @.NAME= NAME
FROM SPROCS
WHERE [ID]= @.ID
AND [TYPE]= @.TYPE

Unfortunately I dont seem to be able to get the output in .Net, or then be able to fill my dataset with the Stored Procedure.
Has anyone done something similar before, or could point me in the right direction to solving this problem.

Thanks
Phil

Since @.NAME is an output parameter, you need to indicate that in your Command object (ParameterDirection.InputOutput or ParameterDirection.Output). That allows the parameter's value to be retrieved after the command has been executed.

Alternatively, you could select the data like you would in a normal data retrieval, and not worry about using an output parameter.

|||

Thanks for your reply Mark, I will try adding the ParameterDirection part.

If I use normal data retrieval how can I select the appropriate stored procedure when I try filling my table adapter from the dataset?

Thanks

|||

I assumed you would be performing an operation to select the stored proc name, then another operation to execute that stored proc.

|||

Yes that is what I am trying to do, but not so sure on how to go about it. Do you have any code examples?

Thanks

|||

hi mate,

Here is a sample

Dim cmd_ObjectpathAsNew SqlCommand("Select * from [" & tabelName &"]", sqlCon)

Dim adapterAsNew SqlDataAdapter(cmd_Objectpath)

Dim resultAsNew DataTable

adapter.Fill(result)

ForEach rowAs DataRowIn result.Rows

////do the process u want

next

Smile

|||

The code I have so far is:

Dim IDAs Int32
Dim TypeAsString

PrivateSub SimpleButton1_Click(ByVal senderAs System.Object,ByVal eAs System.EventArgs)Handles SimpleButton1.Click

ID =Me.TextBox1.Text
Type =Me.TextBox2.Text

Me.SPROCSTableAdapter.Fill(Me.DataSet1.SPROCS, ID, Type)

GetSprocName("AUMS_VALID")

Try

'Logic is a seperate VB file containing further code
Logic.run_SQL_fill_dataset(Me.sqlDataAdapter1, DataSet1.GEN_VALID)
Catch exAs Exception

EndTry

EndSub

PrivateFunction GetSprocName(ByVal st1)AsString
' Gets the names for the sprocs so each table can be filled with differant data. Using value 1 for param 1 just to test
Me.SQLCommand_GetSprocName.Parameters(1).Value = 1
Me.SQLCommand_GetSprocName.Parameters(2).Value = st1.ToString()
Logic.run_SQL_command(Me.sqlConnection1,Me.SQLCommand_GetSprocName)
' This is is where the app seems to fail
ReturnMe.SQLCommand_GetSprocName.Parameters(3).Value.ToString()

EndFunction

**** Code in Logic File: *****

'Sub to run SQLcommand, checks the connection and haddles errors

PublicSharedSub run_SQL_command(ByVal sqlcon1As SqlClient.SqlConnection,ByVal sqlcom1As SqlClient.SqlCommand)

Try
If sqlcon1.State <> ConnectionState.ClosedThen' connection check
sqlcon1.Close()
EndIf

If sqlcon1.State = ConnectionState.ClosedThen' connection check

sqlcon1.Open()

EndIf

sqlcom1.ExecuteNonQuery()

If sqlcon1.State = ConnectionState.OpenThen

sqlcon1.Close()

EndIf

Catch exAs Exception

If sqlcon1.State = ConnectionState.OpenThen

sqlcon1.Close()

EndIf

Error_box(ex,"Error on Running SQL Command")'Can place more better code here later

MsgBox(sqlcom1.CommandText.ToString)

EndTry

EndSub

PublicSharedSub run_SQL_fill_dataset(ByVal sqladapterAs SqlClient.SqlDataAdapter,ByVal datatableAs Data.DataTable)

Try

datatable.Clear()

sqladapter.Fill(datatable)

Catch exAs Exception

Error_box(ex,"Error on fill on dataset.")

EndTry

|||

Hi,


I'm afraid that there's something wrong in your code. What we can provide is a general process of communicating with a stored procedure from a .NET application.

Let's take the stored procedure you provided as the sample.

ALTER PROCEDURE [dbo].[S_SPROC]
( @.ID int, @.TYPE CHAR(10), @.NAME CHAR(20) OUTPUT )
AS

SELECT @.NAME = NAME
FROM SPROCS
WHERE [ID] = @.ID
AND [TYPE] = @.TYPE

In your procs, there are 2 input parameters and an output parameter. Then in your application, you should following the steps below:

1. Create the connection which links to the database.
a) Dim myconn As New SqlConnection(ConnectionString)

2. Create the SqlCommand object which execute the procs.
Dim sc As New SqlCommand()
sc.CommandType = CommandType.StoredProcedure
sc.CommandText = "YourProcsName"
sc.Connection = myconn

3. Setting your parameters and add them to SqlCommand object.

Dim sp1 As New SqlParameter()
sp1.ParameterName = "Parameter1"
sp1.Value = ""

Dim sp2 As New SqlParameter()
sp2.ParameterName = "Parameter2"
sp2.Value = ""

Dim sp3 As New SqlParameter()
sp3.ParameterName = "Parameter3"
sp3.Size = 10
sp3.Direction = ParameterDirection.Output

sc.Parameters.Add(sp1)
sc.Parameters.Add(sp2)
sc.Parameters.Add(sp3)

4. Open the connection, execute the process, and get the output parameter.

myconn.Open()
sc.ExecuteNonQuery()
myconn.Close()
Dim c As String = sp.Value.ToString()


After all, you can get the output parameter from the variable C.

Besides, this is a WebForm support forum, if you are developing WindowForm application, it would be better for you to go to MSDN forum where you can get more help.

Thanks.

|||

Thanks for your reply - it has been a big help.

Phil

Tuesday, March 20, 2012

Problems adding % sign to a number

Hi,
I have a stored procedure which outputs a number as decimal(5,1). I
would like to add a % sign to the end of this number, however when I do
this using CAST(x as VARCHAR)+'%' I get the following error:
Microsoft OLE DB Provider for SQL Server error '80040e07'
Error converting data type varchar to numeric.
The following code works:
SELECT
CASE dbo.ListProfiles.Value
WHEN 0 THEN NULL
ELSE
CAST(((Val1 - Val2)/Val1)*100 AS DECIMAL(5,1))
END AS [Variance],
but when i change it to add the percentage sign (as follows) i get the
above error:
CASE dbo.ListProfiles.Value
WHEN 0 THEN NULL
ELSE
(CAST(
CAST(((Val1-Val2)/Val1)*100 AS DECIMAL(5,1))
AS VARCHAR) + '%')
END AS [Variance],
Can anyone shed any light onto this annoying problem. I have a feeling
that it may just be syntax related, but i've spent ages trying other
things without any success.
Many thanks,
ChrisChris
DECLARE @.dec AS DECIMAL(5,1)
SET @.dec=18.1
SELECT CAST(@.dec AS VARCHAR(10))+'%'
--OR
SELECT CAST(CAST((100-20)/2*100 AS DECIMAL(5,1))AS VARCHAR(10))+'%'
"Chris Dunigan" <chris.dunigan@.agwsha.nhs.uk> wrote in message
news:1113220485.699029.101780@.l41g2000cwc.googlegroups.com...
> Hi,
> I have a stored procedure which outputs a number as decimal(5,1). I
> would like to add a % sign to the end of this number, however when I do
> this using CAST(x as VARCHAR)+'%' I get the following error:
> Microsoft OLE DB Provider for SQL Server error '80040e07'
> Error converting data type varchar to numeric.
> The following code works:
> SELECT
> CASE dbo.ListProfiles.Value
> WHEN 0 THEN NULL
> ELSE
> CAST(((Val1 - Val2)/Val1)*100 AS DECIMAL(5,1))
> END AS [Variance],
> but when i change it to add the percentage sign (as follows) i get the
> above error:
> CASE dbo.ListProfiles.Value
> WHEN 0 THEN NULL
> ELSE
> (CAST(
> CAST(((Val1-Val2)/Val1)*100 AS DECIMAL(5,1))
> AS VARCHAR) + '%')
> END AS [Variance],
> Can anyone shed any light onto this annoying problem. I have a feeling
> that it may just be syntax related, but i've spent ages trying other
> things without any success.
> Many thanks,
> Chris
>|||It's usually best to perform data formatting in application code rather than
in Transact-SQL. That approach is much more robust and scalable.
Hope this helps.
Dan Guzman
SQL Server MVP
"Chris Dunigan" <chris.dunigan@.agwsha.nhs.uk> wrote in message
news:1113220485.699029.101780@.l41g2000cwc.googlegroups.com...
> Hi,
> I have a stored procedure which outputs a number as decimal(5,1). I
> would like to add a % sign to the end of this number, however when I do
> this using CAST(x as VARCHAR)+'%' I get the following error:
> Microsoft OLE DB Provider for SQL Server error '80040e07'
> Error converting data type varchar to numeric.
> The following code works:
> SELECT
> CASE dbo.ListProfiles.Value
> WHEN 0 THEN NULL
> ELSE
> CAST(((Val1 - Val2)/Val1)*100 AS DECIMAL(5,1))
> END AS [Variance],
> but when i change it to add the percentage sign (as follows) i get the
> above error:
> CASE dbo.ListProfiles.Value
> WHEN 0 THEN NULL
> ELSE
> (CAST(
> CAST(((Val1-Val2)/Val1)*100 AS DECIMAL(5,1))
> AS VARCHAR) + '%')
> END AS [Variance],
> Can anyone shed any light onto this annoying problem. I have a feeling
> that it may just be syntax related, but i've spent ages trying other
> things without any success.
> Many thanks,
> Chris
>|||Thanks guys,
nested casts worked a treat
Chris
*** Sent via Developersdex http://www.examnotes.net ***

Monday, March 12, 2012

Problematic Stored Procedures using Views with Triggers

Hi,

I would like to use the view of the company data in the following stored procedures

without needing to pass a value into the CompanyID identity column. Is there a way to do this? The following code contains the view, the insert trigger on the view, and the desired stored procedures.

Also, this code is given me problem as well the error message says it cannot convert varchar to int. This code is located in the insert trigger.

INSERT INTO State(StateName)
VALUES(@.StateName)

Here is the code of the company view, notice the C.CompanyID it is used in the GetCompany stored procedure.

SELECT C.CompanyID, C.CompanyName, A.Street, A.City, S.StateName, A.ZipCode, A.Country, P.PhoneNumber


FROM Company AS C INNER JOIN
Address AS A ON C.AddressID = A.AddressID INNER JOIN
State AS S ON A.StateID = S.StateID INNER JOIN
Phone AS P ON C.PhoneID = P.PhoneID

Here is code for the insert trigger on the view

CREATE TRIGGER InsertTriggerOnCustomerView
ON ViewOfCompany
INSTEAD OF INSERT
AS
BEGIN

DECLARE @.CompanyName VARCHAR(128)
DECLARE @.AddressID INT
DECLARE @.Street VARCHAR(256)
DECLARE @.City VARCHAR(128)
DECLARE @.StateID INT
DECLARE @.StateName VARCHAR(128)
DECLARE @.ZipCode INT
DECLARE @.Country VARCHAR(128)
DECLARE @.PhoneID INT
DECLARE @.PhoneNumber VARCHAR(32)
--DECLARE @.CompanyID INT

SELECT
--@.CompanyID = CompanyID,
@.CompanyName = CompanyName,
@.Street = Street,
@.City = City,
@.StateName = StateName,
@.ZipCode = ZipCode,
@.Country = Country,
@.PhoneNumber = PhoneNumber
FROM INSERTED

INSERT INTO State(StateName)
VALUES(@.StateName)

SET @.StateID = @.@.IDENTITY

INSERT INTO Address(Street, City, StateID, Country, ZipCode)
VALUES(@.Street, @.City, @.StateID, @.ZipCode, @.Country)

SET @.AddressID = SCOPE_IDENTITY()

INSERT INTO Phone(PhoneNumber)
VALUES(@.PhoneNumber)

SET @.PhoneID = SCOPE_IDENTITY()

INSERT INTO Company(CompanyName, AddressID, PhoneID)
VALUES(@.CompanyName, @.AddressID, @.PhoneID)

END

The stored procedures are here.

CREATE PROCEDURE GetCompany
(
@.CompanyID INT
)
AS
BEGIN
SELECT CompanyName,Street, City, StateName,
ZipCode, Country, PhoneNumber
FROM
ViewOfCompany
WHERE
CompanyID = @.CompanyID
END
GO

CREATE PROCEDURE AddCompany
(
@.CompanyName VARCHAR(128),
@.Street VARCHAR(256),
@.City VARCHAR(128),
@.StateName VARCHAR(128),
@.ZipCode VARCHAR(128),
@.Country VARCHAR(128),
@.PhoneNumber VARCHAR(32)
)
AS
BEGIN
INSERT INTO ViewOfCompany
VALUES(@.CompanyName, @.Street, @.City, @.StateName,
@.ZipCode, @.Country, @.PhoneNumber)
END
GO

Hi,

first of all you have a misdesign in your trigger. Triggers occur per statement not per row, so inserting 50 rows in a table will fire the trigger only once not 50 times. In your case the trigger is only executed once which means that it would ingnore the 49 other inserted rows. I would first fix that and perhaps come back with the error line where the error you are describing occurs, marking it with something like -- <<-- Error occurs here.

HTH; Jens Suessmeyer.

http:/www.sqlserver2005.de

|||

I am only needing to add one company at a time. In testing the AddCompany stored procedure with Query Analyzer, it appears to work with the correct parameters. For example,

-- Insert First Company
EXEC AddCompany '', '', '', ...

-- Insert Second Company
EXEC AddCompany '', '', '', ...

With actual values, the records are inserted in the tables.

But, my delimma is in the AddCompany stored procedure I don't want to have to pass in a value for the identity column and I don't want to remove it from the view because I need it for the GetCompany stored procedure. And, I don't want to have to create a seperate view for each scenerio; so, my question is there anyway to achieve the desired goal.

I have been looking at the "check" and "no check" options, but I am not sure how they function.

Problem: Stored Procedures not completing from Web Application

I have several stored procedures that run fine from my SQL Server
database (via the exec command.), though when I call these procedures
from my web application, they do not complete. I have other
procedures that in fact do run fine through my web application though,
so I do not believe its a front-end problem. The procedures only take
about 30 seconds to run from the back-end, so I know its not a time
out issue as well. Does anyone have any ideas?

Thanks in advance."Mike J" <mjewett_2000@.yahoo.com> wrote in message
news:1a9d60fa.0404261152.322ed838@.posting.google.c om...
> I have several stored procedures that run fine from my SQL Server
> database (via the exec command.), though when I call these procedures
> from my web application, they do not complete. I have other
> procedures that in fact do run fine through my web application though,
> so I do not believe its a front-end problem. The procedures only take
> about 30 seconds to run from the back-end, so I know its not a time
> out issue as well. Does anyone have any ideas?
> Thanks in advance.

Can you clarify what you mean by "does not complete"? Do you get an error
message? What version of MSSQL? What's the web platform, eg. ASP, PHP etc.?
If it works fine from Query Analyzer then that suggests an issue on the web
side, but without more information it's hard to say.

Simon|||Mike J (mjewett_2000@.yahoo.com) writes:
> I have several stored procedures that run fine from my SQL Server
> database (via the exec command.), though when I call these procedures
> from my web application, they do not complete. I have other
> procedures that in fact do run fine through my web application though,
> so I do not believe its a front-end problem. The procedures only take
> about 30 seconds to run from the back-end, so I know its not a time
> out issue as well. Does anyone have any ideas?

30 seconds is the default time-out, so timeout problems cannot be ruled
out completely. Do you have proper error handling in your web app?

There are a couple of possible reasons for this, but since you provided
very little information about your code, I can only give some general
comments.

Do you use indexed views or indexes on computed columns? In such case,
you need to issue SET ARITHABORT ON when you connect from your web app
(or make this default for the database with ALTER DATABASE). This setting
is on by default when you run from Query Analyzer.

Even if you don't use indexed views or indexed computed columns, SET
ARITHABORT ON, can still be useful, as you now will get the same plan
as Query Analyzer does.

--
Erland Sommarskog, SQL Server MVP, sommar@.algonet.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp|||"Simon Hayes" <sql@.hayes.ch> wrote in message news:<408d7223$1_3@.news.bluewin.ch>...
> "Mike J" <mjewett_2000@.yahoo.com> wrote in message
> news:1a9d60fa.0404261152.322ed838@.posting.google.c om...
> > I have several stored procedures that run fine from my SQL Server
> > database (via the exec command.), though when I call these procedures
> > from my web application, they do not complete. I have other
> > procedures that in fact do run fine through my web application though,
> > so I do not believe its a front-end problem. The procedures only take
> > about 30 seconds to run from the back-end, so I know its not a time
> > out issue as well. Does anyone have any ideas?
> > Thanks in advance.
> Can you clarify what you mean by "does not complete"? Do you get an error
> message? What version of MSSQL? What's the web platform, eg. ASP, PHP etc.?
> If it works fine from Query Analyzer then that suggests an issue on the web
> side, but without more information it's hard to say.
> Simon

Simon,

Here's some more elaboration. By "does not complete" I mean that the
procedures simply never finish running. They generate no error
messages, and do not lock any objects -- they just dont finish. I
verify this by manually running the procedures in query analyzer
(where they finish quickly) and viewing the results. The strange
thing is that we use over 50 stored procedures, and almost all of them
work -- from both the web application and query analyzer. The couple
procedures that are "not finishing" are not any more complex than the
others.

The web platform we are using is Microsoft asp .NET. We are using SQL
Server 2000 as well.
Any ideas? Thanks.|||Erland Sommarskog <sommar@.algonet.se> wrote in message news:<Xns94D7EF10D40A3Yazorman@.127.0.0.1>...
> Mike J (mjewett_2000@.yahoo.com) writes:
> > I have several stored procedures that run fine from my SQL Server
> > database (via the exec command.), though when I call these procedures
> > from my web application, they do not complete. I have other
> > procedures that in fact do run fine through my web application though,
> > so I do not believe its a front-end problem. The procedures only take
> > about 30 seconds to run from the back-end, so I know its not a time
> > out issue as well. Does anyone have any ideas?
> 30 seconds is the default time-out, so timeout problems cannot be ruled
> out completely. Do you have proper error handling in your web app?
> There are a couple of possible reasons for this, but since you provided
> very little information about your code, I can only give some general
> comments.
> Do you use indexed views or indexes on computed columns? In such case,
> you need to issue SET ARITHABORT ON when you connect from your web app
> (or make this default for the database with ALTER DATABASE). This setting
> is on by default when you run from Query Analyzer.
> Even if you don't use indexed views or indexed computed columns, SET
> ARITHABORT ON, can still be useful, as you now will get the same plan
> as Query Analyzer does.

Erland, yes, we have proper error handling in our web application. We
in fact run many (around 50) stored procedures from our web
application and they complete just fine. The couple procedures that
do not run from the application are not any more complex than the
others.

To elaborate some more on our system, we are using Microsoft .NET, SQL
Server 2000. I have run many tests in query analyzer on our database
server with the procedures in question. They complete accurately and
quickly every time, with no errors. Its only when I call them from
the web app where do not finish. We do not use any indexed views or
computed columns, though I will try to ARITHABOR ON property anyhow.
Any other ideas?
Thanks.|||Mike J (mjewett_2000@.yahoo.com) writes:
> To elaborate some more on our system, we are using Microsoft .NET, SQL
> Server 2000. I have run many tests in query analyzer on our database
> server with the procedures in question. They complete accurately and
> quickly every time, with no errors. Its only when I call them from
> the web app where do not finish. We do not use any indexed views or
> computed columns, though I will try to ARITHABOR ON property anyhow.
> Any other ideas?

With that miniscule of information, no. Well, while you ruled out blocking
in another posting, one possibility is that you manage to block yourself
in the app. When you have a procedure which does not complete, execute
sp_who, and see if any process has a non-zero value in the Blk column.

If there is no blocking, use the Profiler to see where the process gets
stuck.

--
Erland Sommarskog, SQL Server MVP, sommar@.algonet.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp|||I had experienced issues with a store proc executing very quickly in Query Analyzer, but not from my ASP app against a development database. I noticed recently the same issue with the procedure not executing quickly in either QA or the web app.

After checking my table indexes on the dev database I found one joined table that had no index for the fields I was joining on. The index existed in the production database. Once adding that index. the procedure executed in < 1 second in QA and only a couple seconds from the web app.

Hope this helps anyone who's frustrated with similar issues.

Dave

Problem: Stored Procedures not completing from Web Application

I have several stored procedures that run fine from my SQL Server
database (via the exec command.), though when I call these procedures
from my web application, they do not complete. I have other
procedures that in fact do run fine through my web application though,
so I do not believe its a front-end problem. The procedures only take
about 30 seconds to run from the back-end, so I know its not a time
out issue as well. Does anyone have any ideas?

Thanks in advance."Mike J" <mjewett_2000@.yahoo.com> wrote in message
news:1a9d60fa.0404261152.322ed838@.posting.google.c om...
> I have several stored procedures that run fine from my SQL Server
> database (via the exec command.), though when I call these procedures
> from my web application, they do not complete. I have other
> procedures that in fact do run fine through my web application though,
> so I do not believe its a front-end problem. The procedures only take
> about 30 seconds to run from the back-end, so I know its not a time
> out issue as well. Does anyone have any ideas?
> Thanks in advance.

Can you clarify what you mean by "does not complete"? Do you get an error
message? What version of MSSQL? What's the web platform, eg. ASP, PHP etc.?
If it works fine from Query Analyzer then that suggests an issue on the web
side, but without more information it's hard to say.

Simon|||Mike J (mjewett_2000@.yahoo.com) writes:
> I have several stored procedures that run fine from my SQL Server
> database (via the exec command.), though when I call these procedures
> from my web application, they do not complete. I have other
> procedures that in fact do run fine through my web application though,
> so I do not believe its a front-end problem. The procedures only take
> about 30 seconds to run from the back-end, so I know its not a time
> out issue as well. Does anyone have any ideas?

30 seconds is the default time-out, so timeout problems cannot be ruled
out completely. Do you have proper error handling in your web app?

There are a couple of possible reasons for this, but since you provided
very little information about your code, I can only give some general
comments.

Do you use indexed views or indexes on computed columns? In such case,
you need to issue SET ARITHABORT ON when you connect from your web app
(or make this default for the database with ALTER DATABASE). This setting
is on by default when you run from Query Analyzer.

Even if you don't use indexed views or indexed computed columns, SET
ARITHABORT ON, can still be useful, as you now will get the same plan
as Query Analyzer does.

--
Erland Sommarskog, SQL Server MVP, sommar@.algonet.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp|||"Simon Hayes" <sql@.hayes.ch> wrote in message news:<408d7223$1_3@.news.bluewin.ch>...
> "Mike J" <mjewett_2000@.yahoo.com> wrote in message
> news:1a9d60fa.0404261152.322ed838@.posting.google.c om...
> > I have several stored procedures that run fine from my SQL Server
> > database (via the exec command.), though when I call these procedures
> > from my web application, they do not complete. I have other
> > procedures that in fact do run fine through my web application though,
> > so I do not believe its a front-end problem. The procedures only take
> > about 30 seconds to run from the back-end, so I know its not a time
> > out issue as well. Does anyone have any ideas?
> > Thanks in advance.
> Can you clarify what you mean by "does not complete"? Do you get an error
> message? What version of MSSQL? What's the web platform, eg. ASP, PHP etc.?
> If it works fine from Query Analyzer then that suggests an issue on the web
> side, but without more information it's hard to say.
> Simon

Simon,

Here's some more elaboration. By "does not complete" I mean that the
procedures simply never finish running. They generate no error
messages, and do not lock any objects -- they just dont finish. I
verify this by manually running the procedures in query analyzer
(where they finish quickly) and viewing the results. The strange
thing is that we use over 50 stored procedures, and almost all of them
work -- from both the web application and query analyzer. The couple
procedures that are "not finishing" are not any more complex than the
others.

The web platform we are using is Microsoft asp .NET. We are using SQL
Server 2000 as well.
Any ideas? Thanks.|||Erland Sommarskog <sommar@.algonet.se> wrote in message news:<Xns94D7EF10D40A3Yazorman@.127.0.0.1>...
> Mike J (mjewett_2000@.yahoo.com) writes:
> > I have several stored procedures that run fine from my SQL Server
> > database (via the exec command.), though when I call these procedures
> > from my web application, they do not complete. I have other
> > procedures that in fact do run fine through my web application though,
> > so I do not believe its a front-end problem. The procedures only take
> > about 30 seconds to run from the back-end, so I know its not a time
> > out issue as well. Does anyone have any ideas?
> 30 seconds is the default time-out, so timeout problems cannot be ruled
> out completely. Do you have proper error handling in your web app?
> There are a couple of possible reasons for this, but since you provided
> very little information about your code, I can only give some general
> comments.
> Do you use indexed views or indexes on computed columns? In such case,
> you need to issue SET ARITHABORT ON when you connect from your web app
> (or make this default for the database with ALTER DATABASE). This setting
> is on by default when you run from Query Analyzer.
> Even if you don't use indexed views or indexed computed columns, SET
> ARITHABORT ON, can still be useful, as you now will get the same plan
> as Query Analyzer does.

Erland, yes, we have proper error handling in our web application. We
in fact run many (around 50) stored procedures from our web
application and they complete just fine. The couple procedures that
do not run from the application are not any more complex than the
others.

To elaborate some more on our system, we are using Microsoft .NET, SQL
Server 2000. I have run many tests in query analyzer on our database
server with the procedures in question. They complete accurately and
quickly every time, with no errors. Its only when I call them from
the web app where do not finish. We do not use any indexed views or
computed columns, though I will try to ARITHABOR ON property anyhow.
Any other ideas?
Thanks.|||Mike J (mjewett_2000@.yahoo.com) writes:
> To elaborate some more on our system, we are using Microsoft .NET, SQL
> Server 2000. I have run many tests in query analyzer on our database
> server with the procedures in question. They complete accurately and
> quickly every time, with no errors. Its only when I call them from
> the web app where do not finish. We do not use any indexed views or
> computed columns, though I will try to ARITHABOR ON property anyhow.
> Any other ideas?

With that miniscule of information, no. Well, while you ruled out blocking
in another posting, one possibility is that you manage to block yourself
in the app. When you have a procedure which does not complete, execute
sp_who, and see if any process has a non-zero value in the Blk column.

If there is no blocking, use the Profiler to see where the process gets
stuck.

--
Erland Sommarskog, SQL Server MVP, sommar@.algonet.se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techin.../2000/books.asp