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

Friday, March 30, 2012

Problem with SQLBindParameter

I am developing an application, using ODBC, that needs to call a stored procedure in an SQL Server DBMS that has a mix of INPUT and INPUT_OUTPUT parameters. I have the code so that there aren't any errors returned from the function calls but I do not see the bound data change after the SQLExecute() function.

Code snippets follow.

CHAR szStatement[256];

CHAR szBuf[256];

SQLINTEGER irval = 0, filenum = 808042, DoNotCall = 0;
SQLVARCHAR vcPhoneNumber[PHONE_LEN];
SQLVARCHAR vcInstanceCode[INSTANCE_LEN] = {0x20};
SQLVARCHAR vcReason[REASON_LEN] = {0x20};
SQLINTEGER rvalLen = 0, fileLen = 0, noCallLen = 10, phoneLen = SQL_NTS, instanceLen = SQL_NTS, reasonLen = SQL_NTS;

lstrcpy( szStatement, "exec ?= some_proc ?, ?, ?, ?, ?" );

sqlr = SQLPrepare( hStmt, szStatement, lstrlen( szStatement ) );
sqlr = SQLBindParameter( hStmt, 1, SQL_PARAM_OUTPUT, SQL_C_LONG, SQL_INTEGER, 10, 0, &irval, 0, &rvalLen );
sqlr = SQLBindParameter( hStmt, 2, SQL_PARAM_INPUT, SQL_C_LONG, SQL_INTEGER, 10, 0, &filenum, 0, &fileLen );
sqlr = SQLBindParameter( hStmt, 3, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, 10, 0, vcPhoneNumber, 10, &phoneLen );
sqlr = SQLBindParameter( hStmt, 4, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_VARCHAR, 50, 0, vcInstanceCode, 0, &instanceLen );
sqlr = SQLBindParameter( hStmt, 5, SQL_PARAM_INPUT_OUTPUT, SQL_C_LONG, SQL_INTEGER, 1, 0, &DoNotCall, 0, &noCallLen );
sqlr = SQLBindParameter( hStmt, 6, SQL_PARAM_INPUT_OUTPUT, SQL_C_CHAR, SQL_VARCHAR, 250, 0, vcReason, 0, &reasonLen );
sqlr = SQLExecute( hStmt );
if( sqlr == SQL_SUCCESS || sqlr == SQL_SUCCESS_WITH_INFO )

{
sprintf( szBuf, "The return value is %d", irval );
sprintf( szBuf, "The file number is %d", filenum );
sprintf( szBuf, "The phone number is %s", vcPhoneNumber );
sprintf( szBuf, "The instance code is %s", vcInstanceCode );
sprintf( szBuf, "The do not call value is %d", DoNotCall );
sprintf( szBuf, "The reason is %s", vcReason );
}

The problem is that in each of the function calls, the sqlr == SQL_SUCCESS but after the call to SQLExecute(), the data does not change for the output parameters. I can do something similar in other query tools that show the proper values but I am not getting the chanes in my bound variables. I tried adding a call to SQLParamData() but I was having a "Function sequence error" problem.

Any help would be very much appreciated. Thanks in advance.

Hi,

Here're a couple of ideas:

== The behavior of the output parameter may vary based on the actual stored proc, which you are trying to execute. To make sure your parameter description is precise, try using SQLProcedureColumns and examine the types.

== As per MSDN:

If the InputOutputType argument is SQL_PARAM_INPUT_OUTPUT or SQL_PARAM_OUTPUT, ParameterValuePtr points to a buffer in which the driver returns the output value. If the procedure returns one or more result sets, the *ParameterValuePtr buffer is not guaranteed to be set until all result sets/row counts have been processed. If the buffer is not set until processing is complete, the output parameters and return values are unavailable until SQLMoreResults returns SQL_NO_DATA. Calling SQLCloseCursor or SQLFreeStmt with an Option of SQL_CLOSE will cause these values to be discarded.

So what you could do is to fetch the results, call SQLMoreResults appropriately and see if the output parameter will be produced as expected. Also - don't forget the "SET NOCOUNT ON", you might get count tokens as separate resultsets.

HTH,

Jivko Dobrev - MSFT
--
This posting is provided "AS IS" with no warranties, and confers no rights.

|||

At first I was having a problem with syntax errors and some other things that didn't make sense to me. I did some poking around and found that the signature I was given whas different from the signature that was defined in the data. I corrected this and was able to remove the errors. I tried calling SQLFetch() and was receiving an error of "Function sequense error." I can try again. The stored procedure does not return a result set. The return to me is throug a return code, the first parameter, and two in/out parameters, the last two.

I am connecting to someone else's system and they have defined the stored procedure and I don't have any control over how they've defined it.

The SQLExecute is returning SQL_SUCCESS_WITH_INFO and this message. The state is "01000" the native error is "0 The message is: [Microsoft][ODBC SQL Server Driver][SQL Server] The 01000 state is a generic message and that message sure looks generic. :)

I added a call to SQLFetch() after the SQLExecute() and the this is the result. The state is "HY010" the native error is "0 The message is: [Microsoft][ODBC SQL Server Driver]Function sequence error

I'm at a loss as to where to go now.

|||

Hi,

Would you be able to script the stored proc and the related tables/objects and post the script here? If it's not confidential or overly complicated, of course.

I have a suspicion about what you mentioned regarding the procedure not returning any rows. BTW - did you try the SQLMoreResults? Maybe you have multiple resultsets?

Thanks,

Jivko Dobrev - MSFT
--
This posting is provided "AS IS" with no warranties, and confers no rights.

|||

The stored procedure does not return a result set. I don't think SQLMoreResults() would help.

The body, from a snippet I've been given looks something like this:

/*IsOKToCall Procedure*/
CREATE PROCEDURE IsOKToCall
@.FileNumber int,
@.PhoneNumber char(10),
@.Instance varchar(50),
@.DoNotCall int OUTPUT,
@.DoNotCallReason varchar(255) OUTPUT
AS

SELECT @.Instance = ISNULL(@.Instance, 'master')

-- TODO implement this method to return a non-zero in @.DoNotCall if the account should not be contacted.

SELECT @.DoNotCall = 0
SELECT @.DoNotCallReason = ''
Return @.@.Error

GO

Note that this is not the actual procedure. The person that created it has some PRINT statements in the body to show some debug values and there is logic to return different results based on the value passed in the FileNumber parameter. If I change the first parameter to SQL_PARAMETER_RETURN, I get an error when trying to bind the column. The live procedure also defines the OUTPUT parameters as INPUT_OUTPUT.

|||

An update:

I installed SQL Express so I can see what is going on with both sides of the issue. Some of the error message I thought I had were messages from the "print ......" statements the developers put in thier stored procedures. If I call SQLFetch() after the statement execution, I always have an error of "Function Sequense Error" so I don't think that is why I am not getting values back.

Isn't SQLBindParameter() supposed to bind the parameter in the driver so that when the values are returned, they are also changed in the bound parameters? Is there something else I must do to the the correct values?

|||

Someone explain this one to me. The statement being called is "exec ?= IsOkToCall ?, ?, ?, ?, ?" as far and myself and the driver are concerned, there are six parameters. The first one is bound to an INTEGER to receive the @.@.Error value. the second is the ID to search for and is an input type. The third one is a char type and an input parameter. The fourth is a varchar input type. The fifth is an integer and is input_output type to get a result value for logic. And the sixth is a varchar input_output used to recieve the message string. After getting all of the messages from the driver, the sixth parameter is being updated with the value that was set for the fifth result code variable. Changing the parameter numbers to see if there is an off by one error does not fix it.

What should I be looking for for this issue?

|||

Robert,

Do not change the parameter numbers but you should try to call SQLMoreResults until you hit SQL_NO_DATA_FOUND and then see if the output parameters are updated or not. I believe print statements are treated as results and thus have to be flushed before getting to output parameters.

Thanks

Waseem

|||I found that out the hard way. It is after gathering all of the data that I am seeing the mixed up returns. The first parameter that is the return value from the procedure is never set and I still have the wrong value being updated with the integer value and it does not change even after I remove all of the print statements from the stored procedure.|||

Waseem Basheer - MSFT wrote:

Robert,

Do not change the parameter numbers but you should try to call SQLMoreResults until you hit SQL_NO_DATA_FOUND and then see if the output parameters are updated or not. I believe print statements are treated as results and thus have to be flushed before getting to output parameters.

Thanks

Waseem

I found this to be the case and was doing so. I also found where I was setting the destination to the address of a pointer to a character array rather than sending the pointer to the character array. I also found this whole thing to be increadably finicky and full of poorly/non documented quirks. I have the IN/OUT parmeters working but the return code fom a call of "exec ?= my_proc ?, ?, ?" still illudes me. I am still not getting the value for the ?= parameter but I don't think It is too important for me to get this value.

Wednesday, March 28, 2012

Problem with SQL Server

A Stored Procedure has been running fine returning result in 2 secs but
surddenly started taking 2 mins to run. When I run the SQL codes in query
analyser it runs fine. Any idea what the problem may be?
Thanks
Egbon.Have a look at
INF: Troubleshooting Application Performance with SQL Server
http://support.microsoft.com/default.aspx?scid=kb;EN-US;224587
HOW TO: Troubleshoot Slow-Running Queries on SQL Server 7.0 or Later
http://support.microsoft.com/default.aspx?scid=kb;EN-US;243589
INF: Understanding and Resolving SQL Server 7.0
or 2000 Blocking Problems
http://support.microsoft.com/default.aspx?scid=kb;EN-US;Q224453
As well as these articles themselves, they contain links in them to lots
of other performace troubleshooting type articles. Lots of good stuff !
--
HTH
Jasper Smith (SQL Server MVP)
I support PASS - the definitive, global
community for SQL Server professionals -
http://www.sqlpass.org
"Egbon" <Vnjowusi@.gosps.com> wrote in message
news:uTma$F6WDHA.3248@.tk2msftngp13.phx.gbl...
A Stored Procedure has been running fine returning result in 2 secs but
surddenly started taking 2 mins to run. When I run the SQL codes in query
analyser it runs fine. Any idea what the problem may be?
Thanks
Egbon.|||Thanks for the links Jasper. My question was why will it run fine in Query
Analyzer and run slow in Stored Procedure. I can't understand.
Egbon.
"Jasper Smith" <jasper_smith9@.hotmail.com> wrote in message
news:OameON6WDHA.2256@.TK2MSFTNGP10.phx.gbl...
> Have a look at
> INF: Troubleshooting Application Performance with SQL Server
> http://support.microsoft.com/default.aspx?scid=kb;EN-US;224587
> HOW TO: Troubleshoot Slow-Running Queries on SQL Server 7.0 or Later
> http://support.microsoft.com/default.aspx?scid=kb;EN-US;243589
> INF: Understanding and Resolving SQL Server 7.0
> or 2000 Blocking Problems
> http://support.microsoft.com/default.aspx?scid=kb;EN-US;Q224453
> As well as these articles themselves, they contain links in them to lots
> of other performace troubleshooting type articles. Lots of good stuff !
> --
> HTH
> Jasper Smith (SQL Server MVP)
> I support PASS - the definitive, global
> community for SQL Server professionals -
> http://www.sqlpass.org
> "Egbon" <Vnjowusi@.gosps.com> wrote in message
> news:uTma$F6WDHA.3248@.tk2msftngp13.phx.gbl...
> A Stored Procedure has been running fine returning result in 2 secs but
> surddenly started taking 2 mins to run. When I run the SQL codes in query
> analyser it runs fine. Any idea what the problem may be?
> Thanks
> Egbon.
>
>|||Do you mean it runs slow as a stored procedure in Query Analyzer ? i.e. if
you run the contents of the procedure in Query Analyzer does it run quicker
than the exec procedurename ? Sorry if I misunderstood you question, I
thought you meant that in general use by your application the performace of
this procedure was slow which may be cause by blocking etc so profiler would
help to show up the problem. You can also capture the execution plan and
look for differences between the slow and fast executions.
--
HTH
Jasper Smith (SQL Server MVP)
I support PASS - the definitive, global
community for SQL Server professionals -
http://www.sqlpass.org
"Egbon" <Vnjowusi@.gosps.com> wrote in message
news:eAVQIV6WDHA.2424@.TK2MSFTNGP12.phx.gbl...
Thanks for the links Jasper. My question was why will it run fine in Query
Analyzer and run slow in Stored Procedure. I can't understand.
Egbon.
"Jasper Smith" <jasper_smith9@.hotmail.com> wrote in message
news:OameON6WDHA.2256@.TK2MSFTNGP10.phx.gbl...
> Have a look at
> INF: Troubleshooting Application Performance with SQL Server
> http://support.microsoft.com/default.aspx?scid=kb;EN-US;224587
> HOW TO: Troubleshoot Slow-Running Queries on SQL Server 7.0 or Later
> http://support.microsoft.com/default.aspx?scid=kb;EN-US;243589
> INF: Understanding and Resolving SQL Server 7.0
> or 2000 Blocking Problems
> http://support.microsoft.com/default.aspx?scid=kb;EN-US;Q224453
> As well as these articles themselves, they contain links in them to lots
> of other performace troubleshooting type articles. Lots of good stuff !
> --
> HTH
> Jasper Smith (SQL Server MVP)
> I support PASS - the definitive, global
> community for SQL Server professionals -
> http://www.sqlpass.org
> "Egbon" <Vnjowusi@.gosps.com> wrote in message
> news:uTma$F6WDHA.3248@.tk2msftngp13.phx.gbl...
> A Stored Procedure has been running fine returning result in 2 secs but
> surddenly started taking 2 mins to run. When I run the SQL codes in query
> analyser it runs fine. Any idea what the problem may be?
> Thanks
> Egbon.
>
>

Monday, March 26, 2012

Problem with SQL Query Analyzer

Hi,
I have the following problem: if I call a stored procedure from a program (via COM+/OLE DB) I measure the response time and I get something around 400 ms (including reading the data from the result set, a couple of MoveNext operations).
Now if I call the very same stored procedure within the SQL Query Analyzer, it takes almost 8 seconds until I can see the results! Does anybody know why?
Is the Query Analyzer so badly implemented when it reads the results and displays them?
Even if I eliminate the results (by adding select top 0 in my final query in the stored procedure) it still takes about 7 seconds within the Query Analyzer.
My bigger problem is that I use the query analyzer to fine-tune my application and it seems I can't rely on the results, because the same queries run differently once they are called from the application.
It's weird because I also get these confusing response times displayed in the Profiler! At the beginning I thought that the Query Analyzer adds some overhead, but why do I get different times in the Profiler?
Any hints/tips? Did anyone experience that before?
Thanks in advance,
Florin Micle
Execution plans can differ for several reasons. Different SET option is one potential reason. The first thing
to do is to compare the execution plans and see if they are the same or not.
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
"fmicle" <fmicle@.hotmail.com> wrote in message news:824E53F3-AC7C-4C1C-AFD5-06D4609F8714@.microsoft.com...
> Hi,
> I have the following problem: if I call a stored procedure from a program (via COM+/OLE DB) I measure the
response time and I get something around 400 ms (including reading the data from the result set, a couple of
MoveNext operations).
> Now if I call the very same stored procedure within the SQL Query Analyzer, it takes almost 8 seconds until
I can see the results! Does anybody know why?
> Is the Query Analyzer so badly implemented when it reads the results and displays them?
> Even if I eliminate the results (by adding select top 0 in my final query in the stored procedure) it still
takes about 7 seconds within the Query Analyzer.
> My bigger problem is that I use the query analyzer to fine-tune my application and it seems I can't rely on
the results, because the same queries run differently once they are called from the application.
> It's weird because I also get these confusing response times displayed in the Profiler! At the beginning I
thought that the Query Analyzer adds some overhead, but why do I get different times in the Profiler?
> Any hints/tips? Did anyone experience that before?
> Thanks in advance,
> Florin Micle
|||Perhaps your data happened to be cached in some instances. Try clearing the
cache using DBCC DROPCLEANBUFFERS before testing the queries using.
As Tibor mentioned, different execution plans may be another cause, which
you can also capture using Profiler.
Regards
Ray Mond
"fmicle" <fmicle@.hotmail.com> wrote in message
news:824E53F3-AC7C-4C1C-AFD5-06D4609F8714@.microsoft.com...
> Hi,
> I have the following problem: if I call a stored procedure from a program
(via COM+/OLE DB) I measure the response time and I get something around 400
ms (including reading the data from the result set, a couple of MoveNext
operations).
> Now if I call the very same stored procedure within the SQL Query
Analyzer, it takes almost 8 seconds until I can see the results! Does
anybody know why?
> Is the Query Analyzer so badly implemented when it reads the results and
displays them?
> Even if I eliminate the results (by adding select top 0 in my final query
in the stored procedure) it still takes about 7 seconds within the Query
Analyzer.
> My bigger problem is that I use the query analyzer to fine-tune my
application and it seems I can't rely on the results, because the same
queries run differently once they are called from the application.
> It's weird because I also get these confusing response times displayed in
the Profiler! At the beginning I thought that the Query Analyzer adds some
overhead, but why do I get different times in the Profiler?
> Any hints/tips? Did anyone experience that before?
> Thanks in advance,
> Florin Micle
|||Hi, when you look at profiler do you to capture exactly what it being run when the program calls the sp? I ask because unless the inputs are exactly the same you could get differing results. I've seen this with datetime inputs where query plans have been
different depending on the format of the date input. As Tibor says, did the query plan show anything different? I assume they must have done? You've tried the TOP 0 which should eliminate the displaying of the results and as Ray says you can drop the data
from cache (and run CHECKPOINT) to give the two approaches a level playing field. I feel the answer will be in your execution plan and I'd expect either as Tibor says, your SET options will be the root, or that it's perhaps something to do with one or mo
re of your sp inputs.
Alicia
Http://www.sqlporn.co.uk
|||Well, how am I suppose to know how exactly the query is executed and which query plan is taken?
I can see in the Profiler, that the exact same query is launched when I call it from my application and when I call it from the Query Analyzer. The query plan I can only see in the Query Analyzer, if I run my query in it, so I'll never know what plan is a
ctually taken when my query runs from the application.
That's exactly my problem, I can't tune my application properly, since the queries work differently in the Query Analyzer and from my app.
By the way, to answer your questions, the plan is always the same for my query.
I also think there are some bugs in the Profiler.
My stored procedure, let's name it SP1 calls 2 other SP's, which are very fast, let's call them SP2 and SP3.
So SP1 looks something like:
...
EXEC SP2
EXEC SP3
Do some complex queries
...
In the profiler, every time I call SP1, I get 3 SP Completed events, like this (two consecutive calls, you can see the effects of the cache, which is ok):
EventClass TextData Duration
SP:Completedexec SP1 0
SP:Completedexec SP1 0
SP:Completedexec SP1 453
SP:Completedexec SP1 0
SP:Completedexec SP1 0
SP:Completedexec SP1 313
Now, I call the same SP two times from the Query Analyzer, this is what I get in the profiler:
EventClass TextData Duration
SP:Completedexec SP2 0
SP:Completedexec SP3 0
SP:Completedexec SP1 1926
SP:Completedexec SP2 0
SP:Completedexec SP3 0
SP:Completedexec SP1 2005
The profiling mechanisms seem to be different, if the SP1 is called from the Query Analyzer it looks OK, but from my app, there seems to be a bug somwhere in the event handling in the Profiler.
Any ideas?
|||I can't believe this, if I delete the proccache (dbcc freeproccache) I get almost the same response times within QA like from my application!
About 600 ms, which is much better than 2 seconds!
What can make QA generate such a bad query plan?
Another thing: my application (C++) runs as a COM object in COM+. I wrote a small C++ program which does the exact same thing (calls the same stored procedure) and this is slower than when it runs in COM+. I use ATL OLE DB to connect to the DB in both cas
es.
I can only imagine, that there must be some magic in COM+, which sets some parameters differently, thus making the SQL Server run faster/better when called from COM+.
Confusing...
|||> What can make QA generate such a bad query plan?
The cached plan may have been generated for a query that uses parameter
values that do not fall into the same distribution pattern that the later
query has. However, this is unlikely in your case since you mentioned that
they are both using the same query.
I suggest checking the execution plan from both sides. Use Profiler to
capture the execution plan, using the Show Plan Statistics event under the
Performance heading.
Regards
Ray Mond
"fmicle" <fmicle@.hotmail.com> wrote in message
news:D42860F2-6C23-48C0-AA90-9301F2697191@.microsoft.com...
> I can't believe this, if I delete the proccache (dbcc freeproccache) I get
almost the same response times within QA like from my application!
> About 600 ms, which is much better than 2 seconds!
> What can make QA generate such a bad query plan?
> Another thing: my application (C++) runs as a COM object in COM+. I wrote
a small C++ program which does the exact same thing (calls the same stored
procedure) and this is slower than when it runs in COM+. I use ATL OLE DB to
connect to the DB in both cases.
> I can only imagine, that there must be some magic in COM+, which sets some
parameters differently, thus making the SQL Server run faster/better when
called from COM+.
> Confusing...
|||No, you're right, it makes sense. When I call the SP from COM+, I use placeholders and Accessors to bind my parameters.
But I get the exact same query text in the profiler.
On the other hand, if I do the same thing outside COM+, even using the parameters, I still get the bad plan (WITH PREFETCH).
I can only reach almost the same speed outside COM+ if I delete the PROCCACHE.

Friday, March 23, 2012

Problem with sp_sqlagent_get_perf_counters

I have problem with my production server, it is 4 CPUs and they utilized 100%. And i found this stored procedure EXECUTE msdb.dbo.sp_sqlagent_get_perf_counters taking highest CPU time. And i already turned off all the alerts. And i even killed this stored procedure, but still it is executed by some process, i don't know how it is executing.
KiranShut down the SQLAgent service, and these calls will go away. I am going to guess your 100% CPU problem will remain, however.|||I restarted sql agent, but again it is getting fired by some process.|||If you restarted it, of course, SQL Agent will keep sending these queries to the server. What happens when you leave it shut down?|||I have shutdown the sqlAgent in my server, msdb.dbo.sp_sqlagent_get_perf_counters process was killed by system it self. and now the CPU utilization has reduced from 75% to 50%.
But this solution doesn't work for me because, i have some backup jobs running, so i have to start sqlAgent again. Can you suggest me any other solution how to stop running msdb.dbo.sp_sqlagent_get_perf_counters process without stopping sqlAgent.|||Hi, open the code of this sp.
it's loading all enabled alerts int a temp table and then joining it with sysperfinfo table.

as you said the alerts are off; make sure(select * from msdb.dbo.sysalerts where enabled=1) returns nothing.

run this sp manually and check the execution plan, and check if the cpu spikes when u run it manually.sql

Problem with SP_Addlinkedserver when used in stored procedure

I wrote the following stored procedure. Note that SERVER_BK is an ODBC connection on the server that links to the remote server database.

--Creates the stored procedure that will be called in the Tablecounts script to send the comparison out to admins

if exists (select * from dbo.sysobjects where id = object_id(N'sp_compare_table_record_counts') and OBJECTPROPERTY(id, N'IsProcedure') = 1)

drop procedure sp_compare_table_record_counts

go

create proc sp_compare_table_record_counts as

-Creates the connection to the Remote Database. We need to make sure that the

-ODBC connections on each of the Production and Development Servers

-are named the same, so that we can use the same script and it will refer to the correct server

EXEC sp_addlinkedserver

@.server = 'SERVER_BK',

@.srvproduct = '',

@.provider = 'MSDASQL',

@.datasrc = 'SERVER_BK'

EXEC sp_addlinkedsrvlogin 'SERVER_BK', 'true'

set quoted_identifier off

select substring(remote_table.tablename,1,40) as Tablename, local_table.tablerowcount as L_SERVER,

remote_table.tablerowcount as R_SERVER,

case when remote_table.tablerowcount = local_table.tablerowcount then 'Counts Match'

else 'Counts Do Not Match'

end as Result_of_Compare

from OpenQuery([SERVER_BK], 'select * from tablecounts') remote_table, tablecounts local_table

where remote_table.tablename = local_table.tablename

order by Result_of_Compare, Tablename

-- table name on R_SERVER but not on L_SERVER

select substring(local_table.tablename,1,40) as 'Tables not on R_SERVER'

from tablecounts local_table where local_table.tablename not in (select * from OpenQuery([SERVER_BK], 'select tablename from tablecounts'))

-- table name on L_SERVER but not on R_SERVER

select substring(remote_table.tablename,1,40) as 'Tables not on L_SERVER'

from OpenQuery([SERVER_BK], 'select * from tablecounts') remote_table where remote_table.tablename not in (select tablename from tablecounts)

-Deletes the connection to the Remote Database to free up resources. This is just cleanup.

EXEC sp_dropserver 'SERVER_BK', 'droplogins'

I tested, and the stored procedure works OK when it is run as a New Query (i.e. I copy the guts and run it). When I execute the following, it fails:

exec msdb..sp_send_dbmail

@.profile_name = 'DB Mail Profile',

@.recipients = 'Recipient List',

@.query_no_truncate = 25,

@.query_result_separator = ' ',

@.subject = 'Record Counts',

@.query = 'exec db..sp_compare_table_record_counts', <--db is the appropriate db where the sp is

@.body_format = 'text'

Here is the error I get...any ideas would be greatly appreciated. I'm kind of new at this:

Msg 14661, Level 16, State 1, Procedure sp_send_dbmail, Line 476

Query execution failed: Msg 7399, Level 16, State 1, Server L_SERVER, Procedure sp_compare_table_record_counts, Line 28

The OLE DB provider "MSDASQL" for linked server "SERVER_BK" reported an error. The provider did not give any information about the error.

Msg 7303, Level 16, State 1, Server L_SERVER, Procedure sp_compare_table_record_counts, Line 28

Cannot initialize the data source object of OLE DB provider "MSDASQL" for linked server "SERVER_BK".

Msg 0, Level 11, State 0, Line 0

A severe error occurred on the current command. The results, if any, should be discarded.

hope this link may help u :http://sqlserver2000.databases.aspfaq.com/how-do-i-prevent-linked-server-errors.html|||

Whoops, I forgot to mention that this is SQL 2005, SP1. I will check out the link though.

Any other ideas?

The other thing is that this only stops working when I turn this into a SP, when I run the first part (between but not including the create proc...as and the sp_send_dbmail) it seems to work fine.

I just can't turn this into a SP so that I can have DBMAIL execute it and mail the output.

|||

OK, I am going to change the problem a little bit, as I have made some progress. I decided to NOT make this a stored procedure, instead it is just one script now that does all of the work.

However, I still use this part of the code :

EXEC sp_addlinkedserver

@.server = 'SERVER_BK',

@.srvproduct = '',

@.provider = 'MSDASQL',

@.datasrc = 'SERVER_BK'

EXEC sp_addlinkedsrvlogin 'SERVER_BK', 'true'

select substring(local_table.tablename,1,40) as 'Tables not on R_SERVER'

from tablecounts local_table where local_table.tablename not in (select * from OpenQuery([SERVER_BK], 'select tablename from tablecounts'))

This works when I run it as myself, who happens to be an administrator in both locations, and the ODBC connection exists. The problem is when I schedule this as a job. I have a job that runs a tsql command, the job succeeds, but I get this in the log:

Line 59 Cannot initialize the data source object of OLE DB provider "MSDASQL" for linked server "IFS_BK". OLE DB provider "MSDASQL" for linked server "IFS_BK" returned message "[Microsoft][ODBC SQL Server Driver][DBNETLIB]ConnectionOpen (Connect()).". OLE DB provider "MSDASQL" for linked server "IFS_BK" returned message "[Microsoft][ODBC SQL Server Driver][DBNETLIB]SQL Server does not exist or access denied.".

I know that this runs as the SQL Agent account, but I set the account as a db_datareader for that particular database on the other server. The SQL Agent account also is in the local administrators group of the OS on the remote system. Any ideas why this is failing?

|||

EXEC sp_addlinkedsrvlogin 'SERVER_BK', 'true'

when u give this statement the current users credentials are used to connect to the remote server also... check remote server have this user and same password

FROM BOL :

Determines the name of the login used to connect to the remote server. useself is varchar(8), with a default of TRUE.

A value of true specifies that logins use their own credentials to connect to rmtsrvname, with the rmtuser and rmtpassword arguments being ignored. false specifies that the rmtuser and rmtpassword arguments are used to connect to rmtsrvname for the specified locallogin. If rmtuser and rmtpassword are also set to NULL, no login or password is used to connect to the linked server

If remote server is having different user and password then u should use the below statement

EXEC master.dbo.sp_addlinkedsrvlogin @.rmtsrvname=N'Server2',@.useself=N'False',@.locallogin=NULL,@.rmtuser=N'SomeLoginInServer2',@.rmtpassword='Password'

Madhu

|||

Madhu,

Thank you, I think i'm on the right track now. I think I may have confused myself a bit though. The first lines of my script is this:

EXEC master.dbo.sp_addlinkedserver

@.server = 'SERVER2',

@.srvproduct = '',

@.provider = 'MSDASQL',

@.datasrc = 'SERVER2' --This is an ODBC connection that is setup in the system named SERVER. I was trying to do this to avoid having a username and password in a script.

EXEC master.dbo.sp_addlinkedsrvlogin

@.rmtsrvname=N'SERVER2',

@.useself=N'False',

@.locallogin=NULL,

@.rmtuser=N'USERNAME',

@.rmtpassword='PASSWORD'

My expectation is that I can now use a command like this further down in the same script:

OpenQuery([SERVER2], 'select * from TABLENAME')

and it would return everything in the TABLENAME table on the Other Server (server2). When I run the script, instead I get an error:

Msg 7202, Level 11, State 2, Line 67

Could not find server 'SERVER2' in sysservers. Execute sp_addlinkedserver to add the server to sysservers.

But it's not listing any errors creating the connection. What's the key i'm missing?

|||

Madhu,

Thank you, I think i'm on the right track now. I think I may have confused myself a bit though. The first lines of my script is this:

EXEC master.dbo.sp_addlinkedserver

@.server = 'SERVER2',

@.srvproduct = '',

@.provider = 'MSDASQL',

@.datasrc = 'SERVER2' --This is an ODBC connection that is setup in the system named SERVER. I was trying to do this to avoid having a username and password in a script.

EXEC master.dbo.sp_addlinkedsrvlogin

@.rmtsrvname=N'SERVER2',

@.useself=N'False',

@.locallogin=NULL,

@.rmtuser=N'USERNAME',

@.rmtpassword='PASSWORD'

My expectation is that I can now use a command like this further down in the same script:

OpenQuery([SERVER2], 'select * from TABLENAME')

and it would return everything in the TABLENAME table on the Other Server (server2). When I run the script, instead I get an error:

Msg 7202, Level 11, State 2, Line 67

Could not find server 'SERVER2' in sysservers. Execute sp_addlinkedserver to add the server to sysservers.

But it's not listing any errors creating the connection. What's the key i'm missing?

|||

Madhu,

Thank you, I think i'm on the right track now. I think I may have confused myself a bit though. The first lines of my script is this:

EXEC master.dbo.sp_addlinkedserver

@.server = 'SERVER2',

@.srvproduct = '',

@.provider = 'MSDASQL',

@.datasrc = 'SERVER2' --This is an ODBC connection that is setup in the system named SERVER. I was trying to do this to avoid having a username and password in a script.

EXEC master.dbo.sp_addlinkedsrvlogin

@.rmtsrvname=N'SERVER2',

@.useself=N'False',

@.locallogin=NULL,

@.rmtuser=N'USERNAME',

@.rmtpassword='PASSWORD'

My expectation is that I can now use a command like this further down in the same script:

OpenQuery([SERVER2], 'select * from TABLENAME')

and it would return everything in the TABLENAME table on the Other Server (server2). When I run the script, instead I get an error:

Msg 7202, Level 11, State 2, Line 67

Could not find server 'SERVER2' in sysservers. Execute sp_addlinkedserver to add the server to sysservers.

But it's not listing any errors creating the connection. What's the key i'm missing?

|||I did as you suggested, so this makes up the beginning of my script:

EXEC master.dbo.sp_addlinkedserver
@.server = 'SERVER2', --This is an ODBC connection that is setup on the machine.
@.srvproduct = '',
@.provider = 'MSDASQL',
@.datasrc = 'SERVER2'

EXEC master.dbo.sp_addlinkedsrvlogin
@.rmtsrvname=N'SERVER2',
@.useself=N'False',
@.locallogin=NULL,
@.rmtuser=N'USERNAME',
@.rmtpassword='PASSWORD'

Later in the script, I run this:
OpenQuery([SERVER2], 'select * from TABLENAME')

My expectation is that I would get all of the information from the TABLENAME table on SERVER2. Instead, I get this error message when the script runs:
Msg 7202, Level 11, State 2, Line 67
Could not find server 'SERVER2' in sysservers. Execute sp_addlinkedserver to add the server to sysservers.

I think i'm missing one important thing, but I can't figure out what it is.

My thought process is to have 1 script that:
1. Creates the connection to the other server, preferable through the System DSN so that I don't have to store a username/password in the code.
2. Access a table in the remote server that contains a bunch of rowcounts for that server
3. Compare the table from the remote rowcounts to the local rowcounts to make sure they match.

Maybe i'm just doing it the wrong way.
|||

At least you got me thinking...

I found the problem. I created the connection, but forgot to put "GO" to create the connection before I tried using it.

Now, it's working.

Thank you for your help.

Problem with SP_Addlinkedserver when used in stored procedure

I wrote the following stored procedure. Note that SERVER_BK is an ODBC connection on the server that links to the remote server database.

--Creates the stored procedure that will be called in the Tablecounts script to send the comparison out to admins

if exists (select * from dbo.sysobjects where id = object_id(N'sp_compare_table_record_counts') and OBJECTPROPERTY(id, N'IsProcedure') = 1)

drop procedure sp_compare_table_record_counts

go

create proc sp_compare_table_record_counts as

-Creates the connection to the Remote Database. We need to make sure that the

-ODBC connections on each of the Production and Development Servers

-are named the same, so that we can use the same script and it will refer to the correct server

EXEC sp_addlinkedserver

@.server = 'SERVER_BK',

@.srvproduct = '',

@.provider = 'MSDASQL',

@.datasrc = 'SERVER_BK'

EXEC sp_addlinkedsrvlogin 'SERVER_BK', 'true'

set quoted_identifier off

select substring(remote_table.tablename,1,40) as Tablename, local_table.tablerowcount as L_SERVER,

remote_table.tablerowcount as R_SERVER,

case when remote_table.tablerowcount = local_table.tablerowcount then 'Counts Match'

else 'Counts Do Not Match'

end as Result_of_Compare

from OpenQuery([SERVER_BK], 'select * from tablecounts') remote_table, tablecounts local_table

where remote_table.tablename = local_table.tablename

order by Result_of_Compare, Tablename

-- table name on R_SERVER but not on L_SERVER

select substring(local_table.tablename,1,40) as 'Tables not on R_SERVER'

from tablecounts local_table where local_table.tablename not in (select * from OpenQuery([SERVER_BK], 'select tablename from tablecounts'))

-- table name on L_SERVER but not on R_SERVER

select substring(remote_table.tablename,1,40) as 'Tables not on L_SERVER'

from OpenQuery([SERVER_BK], 'select * from tablecounts') remote_table where remote_table.tablename not in (select tablename from tablecounts)

-Deletes the connection to the Remote Database to free up resources. This is just cleanup.

EXEC sp_dropserver 'SERVER_BK', 'droplogins'

I tested, and the stored procedure works OK when it is run as a New Query (i.e. I copy the guts and run it). When I execute the following, it fails:

exec msdb..sp_send_dbmail

@.profile_name = 'DB Mail Profile',

@.recipients = 'Recipient List',

@.query_no_truncate = 25,

@.query_result_separator = ' ',

@.subject = 'Record Counts',

@.query = 'exec db..sp_compare_table_record_counts', <--db is the appropriate db where the sp is

@.body_format = 'text'

Here is the error I get...any ideas would be greatly appreciated. I'm kind of new at this:

Msg 14661, Level 16, State 1, Procedure sp_send_dbmail, Line 476

Query execution failed: Msg 7399, Level 16, State 1, Server L_SERVER, Procedure sp_compare_table_record_counts, Line 28

The OLE DB provider "MSDASQL" for linked server "SERVER_BK" reported an error. The provider did not give any information about the error.

Msg 7303, Level 16, State 1, Server L_SERVER, Procedure sp_compare_table_record_counts, Line 28

Cannot initialize the data source object of OLE DB provider "MSDASQL" for linked server "SERVER_BK".

Msg 0, Level 11, State 0, Line 0

A severe error occurred on the current command. The results, if any, should be discarded.

hope this link may help u :http://sqlserver2000.databases.aspfaq.com/how-do-i-prevent-linked-server-errors.html|||

Whoops, I forgot to mention that this is SQL 2005, SP1. I will check out the link though.

Any other ideas?

The other thing is that this only stops working when I turn this into a SP, when I run the first part (between but not including the create proc...as and the sp_send_dbmail) it seems to work fine.

I just can't turn this into a SP so that I can have DBMAIL execute it and mail the output.

|||

OK, I am going to change the problem a little bit, as I have made some progress. I decided to NOT make this a stored procedure, instead it is just one script now that does all of the work.

However, I still use this part of the code :

EXEC sp_addlinkedserver

@.server = 'SERVER_BK',

@.srvproduct = '',

@.provider = 'MSDASQL',

@.datasrc = 'SERVER_BK'

EXEC sp_addlinkedsrvlogin 'SERVER_BK', 'true'

select substring(local_table.tablename,1,40) as 'Tables not on R_SERVER'

from tablecounts local_table where local_table.tablename not in (select * from OpenQuery([SERVER_BK], 'select tablename from tablecounts'))

This works when I run it as myself, who happens to be an administrator in both locations, and the ODBC connection exists. The problem is when I schedule this as a job. I have a job that runs a tsql command, the job succeeds, but I get this in the log:

Line 59 Cannot initialize the data source object of OLE DB provider "MSDASQL" for linked server "IFS_BK". OLE DB provider "MSDASQL" for linked server "IFS_BK" returned message "[Microsoft][ODBC SQL Server Driver][DBNETLIB]ConnectionOpen (Connect()).". OLE DB provider "MSDASQL" for linked server "IFS_BK" returned message "[Microsoft][ODBC SQL Server Driver][DBNETLIB]SQL Server does not exist or access denied.".

I know that this runs as the SQL Agent account, but I set the account as a db_datareader for that particular database on the other server. The SQL Agent account also is in the local administrators group of the OS on the remote system. Any ideas why this is failing?

|||

EXEC sp_addlinkedsrvlogin 'SERVER_BK', 'true'

when u give this statement the current users credentials are used to connect to the remote server also... check remote server have this user and same password

FROM BOL :

Determines the name of the login used to connect to the remote server. useself is varchar(8), with a default of TRUE.

A value of true specifies that logins use their own credentials to connect to rmtsrvname, with the rmtuser and rmtpassword arguments being ignored. false specifies that the rmtuser and rmtpassword arguments are used to connect to rmtsrvname for the specified locallogin. If rmtuser and rmtpassword are also set to NULL, no login or password is used to connect to the linked server

If remote server is having different user and password then u should use the below statement

EXEC master.dbo.sp_addlinkedsrvlogin @.rmtsrvname=N'Server2',@.useself=N'False',@.locallogin=NULL,@.rmtuser=N'SomeLoginInServer2',@.rmtpassword='Password'

Madhu

|||

Madhu,

Thank you, I think i'm on the right track now. I think I may have confused myself a bit though. The first lines of my script is this:

EXEC master.dbo.sp_addlinkedserver

@.server = 'SERVER2',

@.srvproduct = '',

@.provider = 'MSDASQL',

@.datasrc = 'SERVER2' --This is an ODBC connection that is setup in the system named SERVER. I was trying to do this to avoid having a username and password in a script.

EXEC master.dbo.sp_addlinkedsrvlogin

@.rmtsrvname=N'SERVER2',

@.useself=N'False',

@.locallogin=NULL,

@.rmtuser=N'USERNAME',

@.rmtpassword='PASSWORD'

My expectation is that I can now use a command like this further down in the same script:

OpenQuery([SERVER2], 'select * from TABLENAME')

and it would return everything in the TABLENAME table on the Other Server (server2). When I run the script, instead I get an error:

Msg 7202, Level 11, State 2, Line 67

Could not find server 'SERVER2' in sysservers. Execute sp_addlinkedserver to add the server to sysservers.

But it's not listing any errors creating the connection. What's the key i'm missing?

|||

Madhu,

Thank you, I think i'm on the right track now. I think I may have confused myself a bit though. The first lines of my script is this:

EXEC master.dbo.sp_addlinkedserver

@.server = 'SERVER2',

@.srvproduct = '',

@.provider = 'MSDASQL',

@.datasrc = 'SERVER2' --This is an ODBC connection that is setup in the system named SERVER. I was trying to do this to avoid having a username and password in a script.

EXEC master.dbo.sp_addlinkedsrvlogin

@.rmtsrvname=N'SERVER2',

@.useself=N'False',

@.locallogin=NULL,

@.rmtuser=N'USERNAME',

@.rmtpassword='PASSWORD'

My expectation is that I can now use a command like this further down in the same script:

OpenQuery([SERVER2], 'select * from TABLENAME')

and it would return everything in the TABLENAME table on the Other Server (server2). When I run the script, instead I get an error:

Msg 7202, Level 11, State 2, Line 67

Could not find server 'SERVER2' in sysservers. Execute sp_addlinkedserver to add the server to sysservers.

But it's not listing any errors creating the connection. What's the key i'm missing?

|||

Madhu,

Thank you, I think i'm on the right track now. I think I may have confused myself a bit though. The first lines of my script is this:

EXEC master.dbo.sp_addlinkedserver

@.server = 'SERVER2',

@.srvproduct = '',

@.provider = 'MSDASQL',

@.datasrc = 'SERVER2' --This is an ODBC connection that is setup in the system named SERVER. I was trying to do this to avoid having a username and password in a script.

EXEC master.dbo.sp_addlinkedsrvlogin

@.rmtsrvname=N'SERVER2',

@.useself=N'False',

@.locallogin=NULL,

@.rmtuser=N'USERNAME',

@.rmtpassword='PASSWORD'

My expectation is that I can now use a command like this further down in the same script:

OpenQuery([SERVER2], 'select * from TABLENAME')

and it would return everything in the TABLENAME table on the Other Server (server2). When I run the script, instead I get an error:

Msg 7202, Level 11, State 2, Line 67

Could not find server 'SERVER2' in sysservers. Execute sp_addlinkedserver to add the server to sysservers.

But it's not listing any errors creating the connection. What's the key i'm missing?

|||I did as you suggested, so this makes up the beginning of my script:

EXEC master.dbo.sp_addlinkedserver
@.server = 'SERVER2', --This is an ODBC connection that is setup on the machine.
@.srvproduct = '',
@.provider = 'MSDASQL',
@.datasrc = 'SERVER2'

EXEC master.dbo.sp_addlinkedsrvlogin
@.rmtsrvname=N'SERVER2',
@.useself=N'False',
@.locallogin=NULL,
@.rmtuser=N'USERNAME',
@.rmtpassword='PASSWORD'

Later in the script, I run this:
OpenQuery([SERVER2], 'select * from TABLENAME')

My expectation is that I would get all of the information from the TABLENAME table on SERVER2. Instead, I get this error message when the script runs:
Msg 7202, Level 11, State 2, Line 67
Could not find server 'SERVER2' in sysservers. Execute sp_addlinkedserver to add the server to sysservers.

I think i'm missing one important thing, but I can't figure out what it is.

My thought process is to have 1 script that:
1. Creates the connection to the other server, preferable through the System DSN so that I don't have to store a username/password in the code.
2. Access a table in the remote server that contains a bunch of rowcounts for that server
3. Compare the table from the remote rowcounts to the local rowcounts to make sure they match.

Maybe i'm just doing it the wrong way.
|||

At least you got me thinking...

I found the problem. I created the connection, but forgot to put "GO" to create the connection before I tried using it.

Now, it's working.

Thank you for your help.

Wednesday, March 21, 2012

Problem with SP and uniqueidentifier

I am trying to use a stored procedure and it seems to be giving me a error - I think it doesn't like the uniqueidentifier. I have included the error, stored procedure, and code behind that calls the stored procedure.
Thanks for any help on this!
This is the error I get:
System.ArgumentException: No mapping exists from object type System.Web.UI.WebControls.TextBox to a known
managed provider native type. at System.Data.SqlClient.MetaType.GetMetaTypeFromValue(Type dataType, Object value,
Boolean inferLen) at System.Data.SqlClient.SqlParameter.GetMetaTypeOnly() at
System.Data.SqlClient.SqlParameter.Validate(Int32 index) at System.Data.SqlClient.SqlCommand.BuildParamList(TdsParser
parser, SqlParameterCollection parameters) at System.Data.SqlClient.SqlCommand.BuildExecuteSql(CommandBehavior
behavior, String commandText, SqlParameterCollection parameters, _SqlRPC& rpc) at
System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior,
Boolean returnStream, Boolean async) at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior
cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result) at
System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(DbAsyncResult result, String methodName,
Boolean sendToPipe) at System.Data.SqlClient.SqlCommand.ExecuteNonQuery() at
view_WardSec_PatientLogDetail2.UpdateRecord_buttonClick(Object sender, EventArgs e) in C:\Documents and Settings\
KBuchanan.LMH\Desktop\WebSites\Newest_ER\Views\view_WardSec_PatientLogDetail.aspx.vb:line 358
Here is the stored procedure:
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go


ALTER PROCEDURE [dbo].[UpdateTblVisit_WardSecPatientLog]
(
@.VID decimal,
@.lbl_ChiefComplaint nvarchar(50),
@.TriageDtTmTextBox datetime,
@.PtInRmDtTmTextBox datetime,
@.RnInRmDtTmTextBox datetime,
@.PhyInRmDtTmTextBox datetime,
@.EDHoldDisposDtTmTextBox datetime,
@.DispDschDtTmTextBox datetime,
@.ddlTriageNurse uniqueidentifier,
@.ddlPriNurse uniqueidentifier,
@.ddlEDPhy uniqueidentifier,
@.ddlPriRefPhy decimal,
@.ddlSecRefPhy decimal,
@.ddlDschRN uniqueidentifier,
@.ddlDschPhy uniqueidentifier,
@.ddl_MnsArriv decimal,
@.lblDschDiag nvarchar(50),
@.chkbox_LogComplete bit
)
AS

SET NOCOUNT ON

Update
tblVisit
SET
vChiefComplaint = @.lbl_ChiefComplaint,
vTriageDtTm = @.TriageDtTmTextBox,
vPtInRmDtTm = @.PtInRmDtTmTextBox,
vRnInRmDtTm = @.RnInRmDtTmTextBox,
vPhyInRmDtTm = @.PhyInRmDtTmTextBox,
vEDHoldDisposDtTm = @.EDHoldDisposDtTmTextBox,
vDispDschDtTm = @.DispDschDtTmTextBox,
vTriageRnID = @.ddlTriageNurse,
vRnID = @.ddlPriNurse,
vEdPhyProvID = @.ddlEDPhy,
vPriRefPhyProvID = @.ddlPriRefPhy,
vSecRefPhyProvID = @.ddlSecRefPhy,
vDschRnID = @.ddlDschRN,
vDschPhyID = @.ddlDschPhy,
vMnsArrvID = @.ddl_MnsArriv,
vDschDiag = @.lblDschDiag,
vLogCompletedInd = @.chkbox_LogComplete,
vLogLastEdit = getDate()
WHERE
VID = @.VID

SET NOCOUNT OFF
RETURN

------------------------
Following is the codebehind for a button oncommand event. This code
should execute the stored procedure.
------------------------

Public Sub UpdateRecord_buttonClick(ByVal sender As Object, ByVal e As System.EventArgs)
'Use this to update the CareGiverID into the tbl_Visit table.
Dim sbSql As New System.Text.StringBuilder
sbSql.Append("EXEC UpdateTblVisit_WardSecPatientLog ")
sbSql.Append("@.VID, ")
sbSql.Append("@.lbl_ChiefComplaint, ")
sbSql.Append("@.TriageDtTmTextBox, ")
sbSql.Append("@.PtInRmDtTmTextBox, ")
sbSql.Append("@.RnInRmDtTmTextBox, ")
sbSql.Append("@.PhyInRmDtTmTextBox, ")
sbSql.Append("@.EDHoldDisposDtTmTextBox, ")
sbSql.Append("@.DispDschDtTmTextBox, ")
sbSql.Append("@.ddlTriageNurse, ")
sbSql.Append("@.ddlPriNurse, ")
sbSql.Append("@.ddlEDPhy, ")
sbSql.Append("@.ddlPriRefPhy, ")
sbSql.Append("@.ddlSecRefPhy, ")
sbSql.Append("@.ddlDschRN, ")
sbSql.Append("@.ddlDschPhy, ")
sbSql.Append("@.ddl_MnsArriv, ")
sbSql.Append("@.lblDschDiag, ")
sbSql.Append("@.chkbox_LogComplete, ")
sbSql.Append("@.UserID ")

'Response.Write(sbSql.ToString)
'Response.End()


'Create variables for each of the edited values
Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("ERTrekker_ProdConnectionString1").ConnectionString)
Dim cmd As New SqlCommand(sbSql.ToString(), con)

FindControls(DetailsView, "lbl_ChiefComplaint")
Dim ilbl_ChiefComplaint As TextBox = CType(MyControl, TextBox)
FindControls(DetailsView, "TriageDtTmTextBox")
Dim iTriageDtTmTextBox As TextBox = CType(MyControl, TextBox)
FindControls(DetailsView, "PtInRmDtTmTextBox")
Dim iPtInRmDtTmTextBox As TextBox = CType(MyControl, TextBox)
FindControls(DetailsView, "RnInRmDtTmTextBox")
Dim iRnInRmDtTmTextBox As TextBox = CType(MyControl, TextBox)
FindControls(DetailsView, "PhyInRmDtTmTextBox")
Dim iPhyInRmDtTmTextBox As TextBox = CType(MyControl, TextBox)
FindControls(DetailsView, "EDHoldDisposDtTmTextBox")
Dim iEDHoldDisposDtTmTextBox As TextBox = CType(MyControl, TextBox)
FindControls(DetailsView, "DispDschDtTmTextBox")
Dim iDispDschDtTmTextBox As TextBox = CType(MyControl, TextBox)
FindControls(DetailsView, "ddlTriageNurse")
Dim iddlTriageNurse As DropDownList = CType(MyControl, DropDownList)
FindControls(DetailsView, "ddlPriNurse")
Dim iddlPriNurse As DropDownList = CType(MyControl, DropDownList)
FindControls(DetailsView, "ddlEDPhy")
Dim iddlEDPhy As DropDownList = CType(MyControl, DropDownList)
FindControls(DetailsView, "ddlPriRefPhy")
Dim iddlPriRefPhy As DropDownList = CType(MyControl, DropDownList)
FindControls(DetailsView, "ddlDschRN")
Dim iddlDschRN As DropDownList = CType(MyControl, DropDownList)
FindControls(DetailsView, "ddlDschPhy")
Dim iddlDschPhy As DropDownList = CType(MyControl, DropDownList)
FindControls(DetailsView, "ddl_MnsArriv")
Dim iddl_MnsArriv As DropDownList = CType(MyControl, DropDownList)
FindControls(DetailsView, "lblDschDiag")
Dim ilblDschDiag As TextBox = CType(MyControl, TextBox)
FindControls(DetailsView, "chkbox_LogComplete")
Dim ichkbox_LogComplete As CheckBox = CType(MyControl, CheckBox)


'Add all of the parameters to the command
With cmd.Parameters
.AddWithValue("@.VID", Request("vID"))
.AddWithValue("@.lbl_ChiefComplaint", ilbl_ChiefComplaint.Text.ToString)
.AddWithValue("@.TriageDtTmTextBox", iTriageDtTmTextBox.Text.ToString)
.AddWithValue("@.PtInRmDtTmTextBox", iPtInRmDtTmTextBox)
.AddWithValue("@.RnInRmDtTmTextBox", iRnInRmDtTmTextBox.Text.ToString)
.AddWithValue("@.PhyInRmDtTmTextBox", iPhyInRmDtTmTextBox.Text.ToString)
.AddWithValue("@.EDHoldDisposDtTmTextBox", iEDHoldDisposDtTmTextBox.Text.ToString)
.AddWithValue("@.DispDschDtTmTextBox", iDispDschDtTmTextBox.Text.ToString)
.AddWithValue("@.ddlTriageNurse", iddlTriageNurse.SelectedValue.ToString)
.AddWithValue("@.ddlPriNurse", iddlPriNurse.SelectedValue.ToString)
.AddWithValue("@.ddlEDPhy", iddlEDPhy.SelectedValue.ToString)
.AddWithValue("@.ddlPriRefPhy", iddlPriRefPhy.SelectedValue.ToString)
.AddWithValue("@.ddlDschRN", iddlDschRN.SelectedValue.ToString)
.AddWithValue("@.ddlDschPhy", iddlDschPhy.SelectedValue.ToString)
.AddWithValue("@.ddl_MnsArriv", iddl_MnsArriv.SelectedValue.ToString)
.AddWithValue("@.lblDschDiag", ilblDschDiag.Text.ToString)
.AddWithValue("@.chkbox_LogComplete", ichkbox_LogComplete.Checked.ToString)
.AddWithValue("@.UserID", System.Web.HttpContext.Current.Session("UserID"))

End With

' Open the connection and execute the command
Try
con.Open()
If cmd.ExecuteNonQuery() < 1 Then
Throw New System.Exception("The record was not updated")
End If
Catch ex As Exception
System.Web.HttpContext.Current.Response.Write(ex.ToString())
Finally
If Not con Is Nothing AndAlso con.State = System.Data.ConnectionState.Open Then
con.Close()
End If
End Try
End Sub

(1) You have an additional parameter @.userID that you are trying to force into the stored proc which was not defined.
(2) Your @.VID is a decimal? Doesnt seem like a good idea to put in a where condition. Sometimes 10 may not be equal to 10.0. So make sure you include the precision too in the parameter.
ALTER PROCEDURE [dbo].[UpdateTblVisit_WardSecPatientLog]
(
@.VID decimal(8,2),
also make sure about similar change in the vb code.

Problem with sorting

I am trying to set up custom paging and sorting with my gridview. All is well but the sorting. The problem is with the stored procedure. If I pass in the value @.sortExpression as, for example "discussions_Posts.post_time", i does not sort it at all. But if I replace the @.sortExpression with discussions_Posts.post_time in the actual stored procedure, it gets sorted.

how do I sort this query with a input parameter with values like "discussions_Topics.topic_title" or something?


ALTER PROCEDURE discussions_GetTopicsSubSet
@.startRowIndex as int,
@.maximumRows as int,
@.sortExpression as nvarchar(50),
@.board_id as int
AS

DECLARE @.Topics TABLE
(RowNumber INT,
topic_id INT,
topic_title VARCHAR(50),
topic_replies INT,
topic_views INT,
topic_type INT,
topic_time DATETIME,
post_id int,
post_time DATETIME,
Topic_Author_UserName nvarchar(256),
Topic_Author_ID uniqueidentifier,
Post_Author_Username nvarchar(256),
Post_Author_ID uniqueidentifier)

--DECLARE @.TopicsFrom Datetime

--SELECT @.TopicsFrom = CASE @.TopicsDays WHEN '1' THEN DATEADD(day,-1,getdate()) WHEN '2' THEN DATEADD(day,-7,getdate()) WHEN '3' THEN DATEADD(day,-14,getdate()) WHEN '4' THEN DATEADD(month,-1,getdate()) WHEN '5' THEN DATEADD(month,-3,getdate()) WHEN '6' THEN DATEADD(month,-6,getdate()) WHEN '7' THEN DATEADD(year,-1,getdate()) ELSE DATEADD(year,-1,getdate()) END
-- populate the table CAST(getdate() as int)
INSERT INTO @.Topics
SELECT ROW_NUMBER() OVER (ORDER BY @.sortExpression), discussions_Topics.topic_id, discussions_Topics.topic_title, discussions_Topics.topic_replies, discussions_Topics.topic_views, discussions_Topics.topic_type,discussions_Topics.topic_time, discussions_Posts.post_id, discussions_Posts.post_time, user_1.UserName AS Topic_Author_Username,
user_1.UserId AS Topic_Author_ID, user_2.UserName AS Post_Author_Username, user_2.UserId AS Post_Author_ID
FROM discussions_Topics INNER JOIN
discussions_Posts ON discussions_Posts.post_id = discussions_Topics.topic_last_post_id INNER JOIN
aspnet_Users AS user_1 ON user_1.UserId = discussions_Topics.topic_poster INNER JOIN
aspnet_Users AS user_2 ON user_2.UserId = discussions_Posts.poster_id
WHERE (discussions_Topics.board_id = @.board_id AND
discussions_Topics.topic_type NOT LIKE '1' )

SELECT * from @.Topics
WHERE RowNumber BETWEEN @.startRowIndex AND (@.startRowIndex + @.maximumRows) - 1

Hi ,

Just like dynamic selecting of column names are not permitted by sql server you also can't use dynamic column sorting.

To get the feature that you want. You have to concatenate and create a dynamic query and then execute the query to get your desired result.

Happy Programming,
Anton

Problem with simple Where Clause

Please Help me. I have a Stored Proc as follows:

USE feesched
GO

CREATE PROCEDURE [dbo].[sp_UpdateAveragedMedicare]
AS

-- copy records with alpha in pos 1 that's not J
SELECT SUBSTRING([cpt code],2,LEN([cpt code])),amount,inscode
INTO t_AveragedMedicare
FROM AveragedMedicare
WHERE NOT ISNUMERIC(LEFT([cpt code],1))
AND LEFT([cpt code],1) <> 'J'

I'm getting the following error message:
Server: Msg 156, Level 15, State 1, Procedure sp_UpdateAveragedMedicare, Line 10
Incorrect syntax near the keyword 'AND'.

Can anyone help me out?
Thanks!
Tony"Tony" <topoulos@.mchsi.com> wrote in message
news:6b5416f0.0403041238.31850940@.posting.google.c om...
> Please Help me. I have a Stored Proc as follows:
> USE feesched
> GO
> CREATE PROCEDURE [dbo].[sp_UpdateAveragedMedicare]
> AS
> -- copy records with alpha in pos 1 that's not J
> SELECT SUBSTRING([cpt code],2,LEN([cpt code])),amount,inscode
> INTO t_AveragedMedicare
> FROM AveragedMedicare
> WHERE NOT ISNUMERIC(LEFT([cpt code],1))
> AND LEFT([cpt code],1) <> 'J'
> I'm getting the following error message:
> Server: Msg 156, Level 15, State 1, Procedure sp_UpdateAveragedMedicare,
Line 10
> Incorrect syntax near the keyword 'AND'.
> Can anyone help me out?
> Thanks!
> Tony

ISNUMERIC() returns an integer, so I guess you want this:

WHERE ISNUMERIC(LEFT([cpt code],1)) = 0

However, be aware that ISNUMERIC() returns 1 for many things which you may
not consider to be a number, as it will evaluate conversion to any numeric
data type, not just integers. Perhaps this would be better:

WHERE [cpt code] NOT LIKE '[0-9]%'
AND [cpt code] NOT LIKE 'J%'

Also, note that using procedure names beginning with sp_ is usually reserved
for system stored procedures, and isn't recommended for application code.

Simon

Problem with setting variable values in a loop

In a stored procedure that I'm fixing, there is a problem with assigning variable values inside a loop. The proc is using dynamic SQL and if statements to build all these statements, but I'm having to add a new variable value to it that is throwing it out of whack.

This is the current structure:

SET @.MktNbr = 10

WHILE @.MktNbr < 90

BEGIN

DECLARE @.sqlstmt varchar(1000)

SET @.Market = '0' + CONVERT(char(2),@.MktNbr)

SET @.sqlstmt = ' SELECT (columns)
INTO dbo.table' + @.Market + '
FROM #table
WHERE marketcode = ''' + @.Market + '''
IF @.MktNbr = 50
BEGIN
SET @.MktNbr = 51
END
ELSE
IF @.MktNbr = 51
BEGIN
SET @.MktNbr = 52
END
ELSE
IF @.MktNbr = 52
BEGIN
SET @.MktNbr = 55
END
ELSE
IF @.MktNbr = 55
BEGIN
SET @.MktNbr = 60
END
ELSE
BEGIN
SET @.MktNbr = @.MktNbr + 10
END
EXEC (@.sqlstmt)

END

I'm probably having a blonde moment, but I'm trying to replace the if statements with this:

SET @.MktNbr =
CASE
WHEN @.MktNbr = 10 THEN 20
WHEN @.MktNbr = 20 THEN 30
WHEN @.MktNbr = 30 THEN 40
WHEN @.MktNbr = 40 THEN 50
WHEN @.MktNbr = 50 THEN 51
WHEN @.MktNbr = 51 THEN 52
WHEN @.MktNbr = 52 THEN 55
WHEN @.MktNbr = 55 THEN 60
WHEN @.MktNbr = 60 THEN 70
WHEN @.MktNbr = 70 THEN 80
WHEN @.MktNbr = 80 THEN 81
ELSE @.MktNbr END

Clearly it's wrong because the proc bombs every time with a duplicate table error.

It has been suggested to me that I should hold these market values in an external table. This sounds reasonable but I'm ashamed to admit that I don't know how I'd implement that. Can someone maybe give me a nudge in the right direction?That works fine for me:

DECLARE @.MktNbr int

SET @.MktNbr = 30

SET @.MktNbr =
CASE
WHEN @.MktNbr = 10 THEN 20
WHEN @.MktNbr = 20 THEN 30
WHEN @.MktNbr = 30 THEN 40
WHEN @.MktNbr = 40 THEN 50
WHEN @.MktNbr = 50 THEN 51
WHEN @.MktNbr = 51 THEN 52
WHEN @.MktNbr = 52 THEN 55
WHEN @.MktNbr = 55 THEN 60
WHEN @.MktNbr = 60 THEN 70
WHEN @.MktNbr = 70 THEN 80
WHEN @.MktNbr = 80 THEN 81
ELSE @.MktNbr END

PRINT @.MktNbr|||First...dynamic sql...ugh

Second, why are you setting @.market BEFORE you set @.mrktnmbr?

third, non logged creation of a table will fail the second time you need to do the insert

Can you explain, in business terms, what you are trying to accomplish, or what's been asked of you?|||Clearly it's wrong because the proc bombs every time with a duplicate table error.

Clearly

You can only execute it once per table creation.

Also, again, the assignmnet is out of whack

You will always be trying to create the same table, over and over, because the tablename is not being included in your "logic"|||Clearly it's wrong because the proc bombs every time with a duplicate table error.
My guess is that it fails on dbo.table081, right?

When @.MktNbr reaches 81, your case statement assigns it the new value of 81. The loop will try to make table081 again and fails.
You should set it to 90, so the loop will end.|||The answer is:
@.MktNbr never exceeds 81.|||the biggest wtf here is why are there so many market tables? why not just one?|||But as Brett (and now Rudy... Man I'm slow resonding to this thread) as highlighted above - the code is not good!
Even if you have a fix this is not the way for you to be doing this - explain what you're trying to achieve and hopefully we can prod you towards a better solution :)|||First...dynamic sql...ugh

Second, why are you setting @.market BEFORE you set @.mrktnmbr?

third, non logged creation of a table will fail the second time you need to do the insert

Can you explain, in business terms, what you are trying to accomplish, or what's been asked of you?

Fair points...allow me to address them in turn.

First: yes, dynamic SQL can be yucky but this is not something I developed, I am only making a modification to it. ;)

Second: See first point...I didn't write that, somebody else did. Somebody who no longer works here. :angel:

Third: I've had some ideas of things I'm going to try there so I'll get back to you on that. :)|||Second: See first point...I didn't write that, somebody else did. Somebody who no longer works here. :angel:

There's a reason for that|||Let me ask, do the tables get dropped before you hit this code?

How much data are we talking about?

Why not just hard code the 10 statements and not use dynamic sql?

Or, why not use 1 table and add a column for market code?

Really, all of this makes very little sense

So where did the person go? Burger King?|||There's a reason for that

Yep, there is. Thing is, the bossman doesn't want me to re-write the proc since it works...it's just slow. Right now the priority is just to make that amendment.

If you think that's good, there's some other ones that'd probably turn your hair white.|||Let me ask, do the tables get dropped before you hit this code?

How much data are we talking about?

Why not just hard code the 10 statements and not use dynamic sql?

Or, why not use 1 table and add a column for market code?

Really, all of this makes very little sense

So where did the person go? Burger King?

Don't fret, the person who suggested that I needed to set the variable to 90 was right; it works now. :cool:

Some of the procs do have hard-coded statements. Some of the developers here prefer the dynamic sql because they feel it's easier to maintain. I'm new here so I'm not in a position to tell them their code sucks, particularly since I'm the least experienced of the group. And yes, the tables get dropped; that's the first thing that happens in the proc. Right now we're not doing any design changes.|||that'd probably turn your hair white.

too late, the margarita's took care of that

And btw, what's "Too slow"

Instead of moving the data, why not just create views that are the name of the tables you are creating?

Oh, and if the smucks think your a jr. dba/developer, just keep coming here.

We'll smoke'em|||too late, the margarita's took care of that

And btw, what's "Too slow"

Instead of moving the data, why not just create views that are the name of the tables you are creating?

Oh, and if the smucks think your a jr. dba/developer, just keep coming here.

We'll smoke'em

This particular proc takes over an hour to execute.

Right now I'm testing one that has been executing for over four hours. It's obscene. :Ssql

Problem with Service Broker and DBMail

Hi!
I try to use Service Broker and DBMail together, but have some trouble with that.
I need to create the queue with activation.
And the stored procedure activated on this queue must send e-mail using DBmail.
It's looks simple, but it doesn't work.
There is my script to create objects, but don't forget create dbmail profile before use it.
PS And replace my email by yours

Activated procedures are under the EXECUTE AS context, so they cannot dirrectly invoke procedures in another database (e.g. msdb DBmail procs). The issue is covered on this serios of articles:
http://blogs.msdn.com/remusrusanu/archive/2006/01/12/512085.aspx
http://blogs.msdn.com/remusrusanu/archive/2006/03/01/541882.aspx
http://blogs.msdn.com/remusrusanu/archive/2006/03/07/545508.aspx

The easiest woraround is to mark the database where activation occurs as trustworthy:

ALTER DATABASE [<dbname>] SET TRUSTWORTHY ON;

HTH,
~ Remus

Tuesday, March 20, 2012

Problem with sending mail with Database Mail

Hi


I want to send a simple mail using DATABASE MAIL feature in SQL SERVER 2005.

I've defined a public profile.
I've enabled Database Mail stored procedures through the Surface Area Configuration .

but I can't send a mail with sp_send_dbmail stored procedure in 'msdb' database .


when I execute sp_send_dbmail in the Managment Studio the message is
"Mail queued" but the mail is not sent.

Could it be related to Service Broker?Because the Surface Area Configuration indicates:'this inctance does not have a Service Broker endpoint'.If so, how should I make an endpoint?

here is the log file after executing sp_send_dbmail:


1) "DatabaseMail process is started"

2) "The mail could not be sent to the recipients because of the mail server failure. (Sending Mail using Account 2 (2007-03-08T00:49:29). Exception Message: Could not connect to mail server. (No connection could be made because the target machine actively refused it)."


The DatabaseMail90.exe is triggred ,so the mail is transfered to the mail queue but DatabaseMail90.exe couldn't give the mail to SMTP server.The promlem is what should I do to make DatabaseMail90.exe able to connect to the server?


please help me.

POUYAN

I am moving this to the SQL Server Database Engine forum.

Problem with sending mail with Database Mail


I want to send a simple mail using DATABASE MAIL feature in SQL SERVER 2005.

I've defined a public profile.
I've enabled Database Mail stored procedures through the Surface Area Configuration .

but I can't send a mail with sp_send_dbmail stored procedure in 'msdb' database .


when I execute sp_send_dbmail in the Managment Studio the message is
"Mail queued" but the mail is not sent.

Could it be related to Service Broker?Because the Surface Area Configuration indicates:'this inctance does not have a Service Broker endpoint'.If so, how should I make an endpoint?

here is the log file after executing sp_send_dbmail:


1) "DatabaseMail process is started"

2) "The mail could not be sent to the recipients because of the mail server failure. (Sending Mail using Account 2 (2007-03-08T00:49:29). Exception Message: Could not connect to mail server. (No connection could be made because the target machine actively refused it)."


The DatabaseMail90.exe is triggred ,so the mail is transfered to the mail queue but DatabaseMail90.exe couldn't give the mail to SMTP server.The promlem is what should I do to make DatabaseMail90.exe able to connect to the server?


please help me.

POUYAN

Hi

This article in the forums seems to refer to your problem:

http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=718220&SiteID=1

It think it implies that the machine you are connecting to as an SMTP server is not actually running an SMTP service. You need to check that the machine you have set as the mail server is correct and that SMTP is running on it (on the standard port). There might also be a firewall issue between you and that machine.

I think if it was an authorisation issue with the SMTP server you would get a different error.

|||

Any way thank u.

I'll give it a try

|||

Hi

By default service broker is enabled in each database except 'master' & 'tempdb'

any way again I enabled service broker.

where as DatabaseMail90.exe is triggerd whene I execute sp_send_dbmail,the mail should be given to the queue.but when I execute

sysmail_help_queue_sp to see the queue the 'length' column is 0 which says there is no mail in the queue.I'm confused.

More over I think another problem is that DatabaseMail90.exe can not communicate with the machine(server) .

do u know how I can check communication settings (ports,... ) between SQL SERVER and the server to see what's going on?

thanks.

POUYAN.

|||Database Mail uses SMTP, unlike the old SQL Mail that used Exchange by piggybacking off Outlook/MAPI. In other words, if you're trying to point it to your organization's Exchange server, it won't work unless Exchange is accepting SMTP connections. (I know only slightly less than jack squat about Exchange, so I have no idea how to enable it, or if it's enabled by default.)

If you want to test connectivity, use telnet from the command prompt:

telnet server-address 25

If you see some prompts from the server, or a blank screen with the cursor flashing, then the connection is probably fine. (Hit Ctrl+] and then type quit to exit telnet.) If you receive a message stating that the connection failed, then the issue is most likely that the machine you're pointing at isn't running SMTP. If you can get through with telnet, but DB Mail is still puking, then make sure whatever mail server you're pointing at isn't disallowing your database server to relay mail through it.|||

After doing some efforts now every thing looks to be ok.

in the log :

"Message was sent succesfully "

this shows that the mail was transfered from database mail to SMTP server.

but still the mail is not sent to the email address.

any idea?

|||

After doing some efforts now every thing looks to be ok.

in the log :

"Message was sent succesfully "

this shows that the mail was transfered from database mail to SMTP server.

but still the mail is not sent to the email address.

any idea?

|||In my experience, it's normally been one of two things.

1. Spam filtering. Pretty self-explanatory.

2. The SMTP server you're directly sending to is misconfigured, or otherwise unable to connect to any other mail servers. If you're running IIS SMTP, you can check C:\Inetpub\mailroot\badmail (or whichever directory you've moved Inetpub or badmail to) and see if there are any messages in there that it's given up on trying to deliver. Also, I believe the messages will sit in \Inetpub\mailroot\queue for some time before being thrown in badmail.|||

U where right the problem was spam filtering

Thnks a lot for ur help.

POUYAN.

problem with select stored procedure

i have this stored procedure:

ALTER PROCEDURE dbo.SearchContact
@.searchCriteria nvarchar(128)
AS
Select FstNam1,FstNam02 from Contacts where FstNam1 like '%'+@.searchCriteria+'%'
RETURN

In my .aspx i have a SqlDataSource named SqlDataSource1 which have asocciated this stored procedure to select operation and parameter source of 'searchCriteria' is Control and ControlID is "TextBox1".

Also i have a gridview with source this sqlDataSource1 and a button . When i click this button i want to take value entered in textbox and send it to above stored procedure and show returned infos in my gridview.

i put in

Button1_Click(object sender, EventArgs e)

{

SqlDataSource1.SelectParameters["searchCriteria"].DefaultValue = Session["searchContact"].ToString();

xxxxxx
}

what i need to have to xxxxx to work fine ?

I searched for a solution and i find a lot of posibilities, but all are fragmented.......pls give a solution ...

thx for help.

P.S: Sorry for my english.

try use valid parameter name:

SqlDataSource1.SelectParameters["@.searchCriteria"].DefaultValue = Session["searchContact"].ToString();

|||

Get rid of the Button1_Click event handler, and in the source view of your aspx, make sure that the SqlDataSource is bound to the GridView (DataSourceID="SqlDataSource1"), and add a SelectParameter to the SqlDataSource:

<SelectParameters>
<asp:ControlParameter ControlID="TextBox1"
Name="searchCriteria"
PropertyName="Text"
Type="String" /> />
</SelectParameters>

Also, I don't know why you are storing the search phrase in a Session variable. This doesn't seem necessary, unless you are using it for something else.

|||

nice. I understand do not use session variable for this , but after i do that , what`s next to see a result?

thx.

|||

that`s the code from aspx.cs

protected void Button1_Click(object sender, EventArgs e)
{
try
{
SqlDataSource1.SelectParameters["@.searchCriteria"].DefaultValue = TextBox1.Text;
GridView1.DataBind();
}
catch (Exception ex)
{
}
finally
{

}

that`s the code from aspx.

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1" AllowPaging="True">
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString1 %>"
SelectCommand="SearchContact" SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:ControlParameter ControlID="TextBox1" Name="searchCriteria" PropertyName="Text"
Type="String" />
</SelectParameters>
</asp:SqlDataSource>

when i debug that function, i receive a exception : "System.NullReferenceException: Object reference not set to an instance of an object."

how fix this problem???

|||

Like I said earlier, get rid of the code:

protected void Button1_Click(object sender, EventArgs e)
{
try
{
SqlDataSource1.SelectParameters["@.searchCriteria"].DefaultValue = TextBox1.Text;
GridView1.DataBind();
}
catch (Exception ex)
{
}
finally
{

}

You don't need this. There are two ways to perform data access. One is to use a SqlDataSource and let that do all the work for you, and the other is to write code. You are mixing the two. All you need in your aspx is a textbox, button, gridview and data source control. No code in the code behind at all.

|||

Mikesdotnetting, i remove the "protected void Button1_Click(object sender, EventArgs e)" and in .apx.cs is clear ( no line of code), and .aspx is the same. I don`t see any change.

Pls help me to fix it.

|||when i making test to gridview - testquery - it works fine. To have nothing in Button1_Click , how gridview know to make databind ?? Pls make some light in my mind.|||

Ah - magic.Wink

The SqlDataSource control takes care of creating a connection object, command object, parameter objects and databinding, behind the scenes. All you have to do is tell the datasource (declare) what the connection string is, or where to find it, where any parameter values come from, and their datatype, and what command to execute. Oh, and you have to tell the GridView what datasource to use. It's called the Declarative DataBinding Model. All the internal workings of how it does its thing are abstracted away from the user. Perfect OOP.Big Smile

|||

And after all you said, i didn`t make it to work :( .

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Find" Width="65px" /*not have on click, as you said*/ /><br />

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource1" AllowPaging="True">
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:MyConnectionString1 %>"
SelectCommand="SearchContact" SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:ControlParameter ControlID="TextBox1" Name="searchCriteria" PropertyName="Text"
Type="String" />
</SelectParameters>
</asp:SqlDataSource>

when i select gridview "configure data source" an make a test query i works fine, no problem. ...but when i run the page in browser and i click on button ......nothing ...

What are my mistakes?? pls write for me some code...how to do...thx a lot

|||Change AutogenerateColumns to true in the GridView, and in the configuration for the GridView, click Refresh Schema. If you set it to false, you have to create your own ItemTemplate.|||

thx man ! it works.

Thx a lot !

|||

hi

if that work then mark as answer

thanks

|||

there i have another problem:

my gridview is populated ok , but works very slowly. I need to have about 20 - 40 textboxes and dropdownlists on my page. i put on page a scriptManager and all control are putted in an UpdatePanel . when i search a item in database , my gridview is populated very slowly..

what is wrong?..how can i fix this problem?

|||If you have a different problem, you should start a new thread in an appropriate forum for the problem. This one has been marked as resolved, so I'm probably the only person reading it now. Your new problem is related to AJAX. The subject of this thread is stored procedures. No one who knows about AJAX will see your question. I don't use ASP.NET AJAX, so I am afraid I can't help you with this one.

Monday, March 12, 2012

Problem with Saving a Stored Procedure

I have had the same problem. In the past I had the sql commands in the code. Last project was with SQL2000 and I decided to add store procedures part as a learning tool and part to better control the code. With the current project I am using SQL2005 and have a ummm fun time with the learning curve.

Below is my stored procedure.

USE [AdventureWorks]

GO

SET ANSI_NULLS ON

GO

SET QUOTED_IDENTIFIER ON

GO

ALTER Procedure [dbo].[WDR_CountryAdd]

(

@.CountryName nvarchar(50),

@.CountryID int OUTPUT

)

AS

INSERT INTO Country

(

CountryName

)

VALUES

(

@.CountryName

)

SELECT

@.CountryID = @.@.Identity

When I hit the execute button, I get the following error.

Msg 208, Level 16, State 6, Procedure WDR_CountryAdd, Line 24

Invalid object name 'WDR_CountryAdd'.

I I know that it does not exist as that is what I am trying to do, create it. I have checked to make sure that I am on the currect database. So how do I associate this procedure with the data base? Do I need to write a SQL query to create the procedure? Maybe that is the answer and then just modify it.

If it doesn't exists, you need to use a CREATE PROCEDURE statement instead of an ALTER PROCEDURE statement.|||

Arnie

I appreciate the fast response.

I used a create and it ran successfully. However, it still did not show up under the stored procedures. So if it does not show up in the list, how do I access it from my web application? With SQL 2000 I just did a right click create new, did the code and it saved it to the list and then I accessed it. I was planning on a code along the lines of WDR_CountryAdd("USA") (of course in the proper codes)

Now here is a beginners question, When I first execute this procedure, do I need to supply the parameters for it to successfully attach to the database?

Jerry

|||

Never Mind. I ran the CREATE again and it worked very well. Must of had a brain dead moment there.

Thanks for the help. I have learned a lot from this forum.

Jerry

Problem with Returning a recordset from a stored procedure in ADO/VBScript

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.A good place to start looking is the ADO Connection Error collection. Check to see if Connect.Errors.Count > 0. If so, you will probably find your problem there.

Also, you can try adding SET NOCOUNT ON at the beginning of your SP, and SET NOCOUNT OFF at the end, before you return your recordset. Sometimes the command object stops asking for data when it gets the "X records affected" messages.

Finally, if that doesn't work, try being more explicit with your parameter naming. A good (and more readable) approach would be to use the CreateParameter function.

CreateParameter([Name As String], [Type As DataTypeEnum = adEmpty], [Direction As ParameterDirectionEnum = adParamInput], [Size As ADO_LONGPTR], [Value]) As Parameter

Assume your parameter is an INT named @.my_param

cmm.Parameters.Append cmm.CreateParameter("@.my_param",3,1, 4,client_id)

[Note: the values of DataTypeEnum and ParameterDriectionEnum can be found at http://msdn.microsoft.com/library/default.asp?url=/library/en-us/ado270/htm/mdaenumnz_2.asp ]

Hope this helps...|||Ahh. Thank you so much. It was the NOCOUNT property.

Problem with return value of stored procedure when using tableadapters

hello

Could you please help me with this problem?

I have a stored procedure like this:

ALTER PROCEDUREdbo.UniqueChannelName

(

@.UserNamenvarchar(50),

@.ChannelNamenvarchar(50)

)

AS

return5;

Then inside of my dataset, I added a new query(dataset1.QueriesTableAdapter) to handle above mentioned stored procedure. Properties window is showing that return type of this adapter is of type int32 as we expected to be.

now I want to use it inside of my code:

DataSet1TableAdapters.QueriesTableAdapter b =new DataSet1TableAdapters.QueriesTableAdapter();

int i;

i=Convert.ToInt32( b.UniqueChannelName("Ahmad","test"));

as you may guess, the return type of b.UniqueChannelName("Ahmad","test") is object and needs to be type-casted before assigning it's value to i; but even after explicit type casting, the value of i is always set to 0, not 5.

could you please show me the way?

many thanks in advance

There is a bug / undocumented feature / downright bad design in ADO.NET whereby a stored procedure with both output parameters and a dataset to return, will not populate the output parameter until all the dataset has been read.

Try reading the dataset to completion before reading the output parameter, otherwise you will have to split your stored procedure into an output parameter part and a dataset part.

|||

Thanks for your fast response.

I'm new to ado.net and couldn't understand what you mean by reading the dataset. Could you please refer me to an example?

thanks

|||

>I'm new to ado.net and couldn't understand what you mean by reading the dataset.

Try assigning the dataset to the control, databind it and then read the output parameter value.

|||

Thanks, Iwill try it tomorrow.

|||

My code is now like this:

DataSet1TableAdapters.QueriesTableAdapter b =new DataSet1TableAdapters.QueriesTableAdapter();

int i;

GridView2.DataSource = b.UniqueChannelName("Ahmad","test");

GridView2.DataBind();

i=Convert.ToInt32( b.UniqueChannelName("Ahmad","test"));

But the problem persists

|||

Please post your stored procedure.

|||ALTER PROCEDURE dbo.UniqueChannelName(@.UserName nvarchar(50),@.ChannelName nvarchar(50))ASdeclare @.Out intSET NOCOUNT ON;return 5;|||

ALTER PROCEDURE dbo.UniqueChannelName

(

@.UserName nvarchar(50),

@.ChannelName nvarchar(50)

)

AS

declare @.Out int

SET NOCOUNT ON;

//return 5;

SET @.OUT=5

// You can get it using AddOutParameter and getOutParameter method

Do not forget to mark as an answer on the post that helped you.

|||

You need to modify your stored procedure to
ALTER PROCEDURE dbo.UniqueChannelName
( @.UserName nvarchar(50),
@.ChannelName nvarchar(50),
@.Out INT OUTPUT -- To get output from a stored procedure parameter you must define it as such
)AS
SET NOCOUNT ON;
SET @.OUT=5

The calling code will need to change

|||

Thanks

Do you mean I must use Database classs and I can't use dataset for my purpose?Infact I prefred using datasets.

Plus

@.out was a local variable inside my code, can it send data out?

Plus

Later I want to change my stored procedure to a select statement like this:

select @.out=count(Autonumber) from ...

what should I do for returning the value?

again thanks for your incorporation

|||

Ok

nowUniqueChannelName method became like this:

UniqueChannelName(string UserName, string ChannelName, ref int? Out)

but unfortunately I don't know how to use the last parameter. could you please help?

thanks

|||

> Plus @.out was a local variable inside my code, can it send data out?

It has to become an output argument of the stored procedure. A local variable is purely local.

For small datasets selected by a SELECT A, B, C FROM FRED, they can be modified to SELECT @.out AS OUT, A, B, C FROM FRED

If the dataset is small the overhead is minimal, otherwise you need to formally define a Command object with all the arguments.

|||

Dear Allstar,

You gave too much of information to me. thanks alot.

I think if you give me a guide on using that reference variable, my questions will be finished.

Any how, thanks alot.

|||I am looking for an example in an old VS2003 project, but the search is taking longer than I anticipated.

Friday, March 9, 2012

Problem with replication

When I try to insert a new record in the subscriber, into a published table, I get a error, saying that it could not execute a stored procedure in the remote server SQLOLEDB. But I when I insert a new record in the publisher, it works correctly, transmitting the changes to the subscriber. What's wrong with it? Both systems are windows 2000 server, with sql server 2000. Thanks.Please give us an idea what type of replication it is?|||- Do you have latest fix installed on the subscriber?
- Does the insertion fire any triggers?|||It is a transactional replication. The error occurs when the subscriber is calling the remote stored procedure in the publisher, which updates the original table.

Saturday, February 25, 2012

Problem with Query

Hi,

Here is the part of a stored procedure

declare @.startDate datetime
declare @.endDate datetime
set @.startDate = '12/1/2007 12:00:00 AM'
set @.endDate = '12/20/2007 12:00:00 AM'

--case1:
--The below query executes fine and displays records (count 50)
select * from Employee
where dtsubmittimestamp BETWEEN @.startDate and @.endDate

--case2:
--The below query executes fine and displays records (count 37)
select * from Employee
where iclientaccid = 51

--case3:
--The below query executes but no records are displayed (0 records)
select * from Employee
where iclientaccid = 51
and dtsubmittimestamp BETWEEN @.startDate and @.endDate

--case4:
--The below query executes but no records are displayed (0 records)
select * from Employee
where dtsubmittimestamp BETWEEN @.startDate and @.endDate
and iclientaccid = 51

I am unable to find out why it doesn't display any records in cases 3 and 4

Please help me. Thanks in advance.

Try...

where (iclientaccid = 51)and (dtsubmittimestampBETWEEN @.startDateand @.endDate)
|||

Your iclientaccid = 51 is not in the range of hardcoded statrtdate and endDate

Satalaj.