Showing posts with label procedure. Show all posts
Showing posts with label procedure. 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.

problem with space

HI friends,
I've got one question. When I realize "log in" in my sql server, I am using
SP like this:
CREATE Procedure CustomerLogin
(
@.Email nvarchar(30),
@.Pwd nvarchar(10),
@.CustomerID int OUTPUT
)
AS
SELECT
@.CustomerID = CustomerID
FROM
Customers
WHERE
Email = @.Email COLLATE SQL_Latin1_General_CP1_CS_AS
AND
Pwd =@.Pwd COLLATE SQL_Latin1_General_CP1_CS_AS
IF @.@.Rowcount < 1
SELECT
@.CustomerID = 0
GO
The problem is that if the password is "qweqwe" and I try to log in with
"qweqwe " or even "qweqwe " (I mean with space after last symbol) it
succeed!!!
Interesting but if I try to log in with " qweqwe" (I mean with space in
beginning) it not succeed.
I don't know why. Could you please somebody help me?Because the trailing spaces are being removed. When you use
the password ' qweqwe' it's not a trailing space so it is
included in the string.
If you want to test to verify, just print out a
len(@.password) before the select.
-Sue
On Tue, 22 Feb 2005 01:45:47 -0000, "Mango"
<mitko762002@.yahoo.com> wrote:

>HI friends,
>I've got one question. When I realize "log in" in my sql server, I am using
>SP like this:
>CREATE Procedure CustomerLogin
>(
> @.Email nvarchar(30),
> @.Pwd nvarchar(10),
> @.CustomerID int OUTPUT
> )
>AS
>
>SELECT
> @.CustomerID = CustomerID
>
>FROM
> Customers
>
>WHERE
> Email = @.Email COLLATE SQL_Latin1_General_CP1_CS_AS
> AND
> Pwd =@.Pwd COLLATE SQL_Latin1_General_CP1_CS_AS
>
>IF @.@.Rowcount < 1
>SELECT
> @.CustomerID = 0
>GO
>
>The problem is that if the password is "qweqwe" and I try to log in with
>"qweqwe " or even "qweqwe " (I mean with space after last symbol) it
>succeed!!!
>Interesting but if I try to log in with " qweqwe" (I mean with space in
>beginning) it not succeed.
>I don't know why. Could you please somebody help me?
>

problem with space

HI friends,
I've got one question. When I realize "log in" in my sql server, I am using
SP like this:
CREATE Procedure CustomerLogin
(
@.Email nvarchar(30),
@.Pwd nvarchar(10),
@.CustomerID int OUTPUT
)
AS
SELECT
@.CustomerID = CustomerID
FROM
Customers
WHERE
Email = @.Email COLLATE SQL_Latin1_General_CP1_CS_AS
AND
Pwd =@.Pwd COLLATE SQL_Latin1_General_CP1_CS_AS
IF @.@.Rowcount < 1
SELECT
@.CustomerID = 0
GO
The problem is that if the password is "qweqwe" and I try to log in with
"qweqwe " or even "qweqwe " (I mean with space after last symbol) it
succeed!!!
Interesting but if I try to log in with " qweqwe" (I mean with space in
beginning) it not succeed.
I don't know why. Could you please somebody help me?
Post the DDL for your Customers table. Specifically, what's datatype of
the Pwd column?
*mike hodgson* |/ database administrator/ | mallesons stephen jaques
*T* +61 (2) 9296 3668 |* F* +61 (2) 9296 3885 |* M* +61 (408) 675 907
*E* mailto:mike.hodgson@.mallesons.nospam.com |* W* http://www.mallesons.com
Mango wrote:

>HI friends,
>I've got one question. When I realize "log in" in my sql server, I am using
>SP like this:
>CREATE Procedure CustomerLogin
>(
> @.Email nvarchar(30),
> @.Pwd nvarchar(10),
> @.CustomerID int OUTPUT
>)
>AS
>
>SELECT
> @.CustomerID = CustomerID
>
>FROM
> Customers
>
>WHERE
> Email = @.Email COLLATE SQL_Latin1_General_CP1_CS_AS
> AND
> Pwd =@.Pwd COLLATE SQL_Latin1_General_CP1_CS_AS
>
>IF @.@.Rowcount < 1
>SELECT
> @.CustomerID = 0
>GO
>
>The problem is that if the password is "qweqwe" and I try to log in with
>"qweqwe " or even "qweqwe " (I mean with space after last symbol) it
>succeed!!!
>Interesting but if I try to log in with " qweqwe" (I mean with space in
>beginning) it not succeed.
>I don't know why. Could you please somebody help me?
>
>
|||the datatype of Pwd is nvarchar. I found that is working corect if i write
it like this:
CREATE Procedure CustomerLogin
(
@.Email nvarchar(80),
@.Pwd nvarchar(50),
@.CustomerID int OUTPUT
)
AS
SELECT
@.CustomerID = CustomerID
FROM
Customers
WHERE
Email + '1' = @.Email COLLATE SQL_Latin1_General_CP1_CS_AS + '1'
AND
Pwd + '1'=@.Pwd COLLATE SQL_Latin1_General_CP1_CS_AS + '1'
IF @.@.Rowcount < 1
SELECT
@.CustomerID = 0
GO
But I am sure this is not the best approach
"Mike Hodgson" <mike.hodgson@.mallesons.nospam.com> wrote in message
news:#t9fdRIGFHA.2608@.TK2MSFTNGP10.phx.gbl...
> Post the DDL for your Customers table. Specifically, what's datatype of
> the Pwd column?
> --
> *mike hodgson* |/ database administrator/ | mallesons stephen jaques
> *T* +61 (2) 9296 3668 |* F* +61 (2) 9296 3885 |* M* +61 (408) 675 907
> *E* mailto:mike.hodgson@.mallesons.nospam.com |* W*
http://www.mallesons.com[vbcol=seagreen]
>
> Mango wrote:
using[vbcol=seagreen]
it
>

Friday, March 23, 2012

problem with space

HI friends,
I've got one question. When I realize "log in" in my sql server, I am using
SP like this:
CREATE Procedure CustomerLogin
(
@.Email nvarchar(30),
@.Pwd nvarchar(10),
@.CustomerID int OUTPUT
)
AS
SELECT
@.CustomerID = CustomerID
FROM
Customers
WHERE
Email = @.Email COLLATE SQL_Latin1_General_CP1_CS_AS
AND
Pwd =@.Pwd COLLATE SQL_Latin1_General_CP1_CS_AS
IF @.@.Rowcount < 1
SELECT
@.CustomerID = 0
GO
The problem is that if the password is "qweqwe" and I try to log in with
"qweqwe " or even "qweqwe " (I mean with space after last symbol) it
succeed!!!
Interesting but if I try to log in with " qweqwe" (I mean with space in
beginning) it not succeed.
I don't know why. Could you please somebody help me?Post the DDL for your Customers table. Specifically, what's datatype of
the Pwd column?
*mike hodgson* |/ database administrator/ | mallesons stephen jaques
*T* +61 (2) 9296 3668 |* F* +61 (2) 9296 3885 |* M* +61 (408) 675 907
*E* mailto:mike.hodgson@.mallesons.nospam.com |* W* http://www.mallesons.com
Mango wrote:

>HI friends,
>I've got one question. When I realize "log in" in my sql server, I am using
>SP like this:
>CREATE Procedure CustomerLogin
>(
> @.Email nvarchar(30),
> @.Pwd nvarchar(10),
> @.CustomerID int OUTPUT
> )
>AS
>
>SELECT
> @.CustomerID = CustomerID
>
>FROM
> Customers
>
>WHERE
> Email = @.Email COLLATE SQL_Latin1_General_CP1_CS_AS
> AND
> Pwd =@.Pwd COLLATE SQL_Latin1_General_CP1_CS_AS
>
>IF @.@.Rowcount < 1
>SELECT
> @.CustomerID = 0
>GO
>
>The problem is that if the password is "qweqwe" and I try to log in with
>"qweqwe " or even "qweqwe " (I mean with space after last symbol) it
>succeed!!!
>Interesting but if I try to log in with " qweqwe" (I mean with space in
>beginning) it not succeed.
>I don't know why. Could you please somebody help me?
>
>|||the datatype of Pwd is nvarchar. I found that is working corect if i write
it like this:
CREATE Procedure CustomerLogin
(
@.Email nvarchar(80),
@.Pwd nvarchar(50),
@.CustomerID int OUTPUT
)
AS
SELECT
@.CustomerID = CustomerID
FROM
Customers
WHERE
Email + '1' = @.Email COLLATE SQL_Latin1_General_CP1_CS_AS + '1'
AND
Pwd + '1'=@.Pwd COLLATE SQL_Latin1_General_CP1_CS_AS + '1'
IF @.@.Rowcount < 1
SELECT
@.CustomerID = 0
GO
But I am sure this is not the best approach
"Mike Hodgson" <mike.hodgson@.mallesons.nospam.com> wrote in message
news:#t9fdRIGFHA.2608@.TK2MSFTNGP10.phx.gbl...
> Post the DDL for your Customers table. Specifically, what's datatype of
> the Pwd column?
> --
> *mike hodgson* |/ database administrator/ | mallesons stephen jaques
> *T* +61 (2) 9296 3668 |* F* +61 (2) 9296 3885 |* M* +61 (408) 675 907
> *E* mailto:mike.hodgson@.mallesons.nospam.com |* W*
http://www.mallesons.com
>
> Mango wrote:
>
using[vbcol=seagreen]
it[vbcol=seagreen]
>sql

problem with space

HI friends,
I've got one question. When I realize "log in" in my sql server, I am using
SP like this:
CREATE Procedure CustomerLogin
(
@.Email nvarchar(30),
@.Pwd nvarchar(10),
@.CustomerID int OUTPUT
)
AS
SELECT
@.CustomerID = CustomerID
FROM
Customers
WHERE
Email = @.Email COLLATE SQL_Latin1_General_CP1_CS_AS
AND
Pwd =@.Pwd COLLATE SQL_Latin1_General_CP1_CS_AS
IF @.@.Rowcount < 1
SELECT
@.CustomerID = 0
GO
The problem is that if the password is "qweqwe" and I try to log in with
"qweqwe " or even "qweqwe " (I mean with space after last symbol) it
succeed!!!
Interesting but if I try to log in with " qweqwe" (I mean with space in
beginning) it not succeed.
I don't know why. Could you please somebody help me?This is a multi-part message in MIME format.
--020209070906080502050607
Content-Type: text/plain; charset=ISO-8859-1; format=flowed
Content-Transfer-Encoding: 7bit
Post the DDL for your Customers table. Specifically, what's datatype of
the Pwd column?
--
*mike hodgson* |/ database administrator/ | mallesons stephen jaques
*T* +61 (2) 9296 3668 |* F* +61 (2) 9296 3885 |* M* +61 (408) 675 907
*E* mailto:mike.hodgson@.mallesons.nospam.com |* W* http://www.mallesons.com
Mango wrote:
>HI friends,
>I've got one question. When I realize "log in" in my sql server, I am using
>SP like this:
>CREATE Procedure CustomerLogin
>(
> @.Email nvarchar(30),
> @.Pwd nvarchar(10),
> @.CustomerID int OUTPUT
>)
>AS
>
>SELECT
> @.CustomerID = CustomerID
>
>FROM
> Customers
>
>WHERE
> Email = @.Email COLLATE SQL_Latin1_General_CP1_CS_AS
> AND
> Pwd =@.Pwd COLLATE SQL_Latin1_General_CP1_CS_AS
>
>IF @.@.Rowcount < 1
>SELECT
> @.CustomerID = 0
>GO
>
>The problem is that if the password is "qweqwe" and I try to log in with
>"qweqwe " or even "qweqwe " (I mean with space after last symbol) it
>succeed!!!
>Interesting but if I try to log in with " qweqwe" (I mean with space in
>beginning) it not succeed.
>I don't know why. Could you please somebody help me?
>
>
--020209070906080502050607
Content-Type: text/html; charset=ISO-8859-1
Content-Transfer-Encoding: 7bit
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta content="text/html;charset=ISO-8859-1" http-equiv="Content-Type">
</head>
<body bgcolor="#ffffff" text="#000000">
<tt>Post the DDL for your Customers table. Specifically, what's
datatype of the Pwd column?</tt><br>
<div class="moz-signature">
<title></title>
<meta http-equiv="Content-Type" content="text/html; ">
<p><span lang="en-au"><font face="Tahoma" size="2">--<br>
</font> </span><b><span lang="en-au"><font face="Tahoma" size="2">mike
hodgson</font></span></b><span lang="en-au"> <font face="Tahoma"
size="2">|</font><i><font face="Tahoma"> </font><font face="Tahoma"
size="2"> database administrator</font></i><font face="Tahoma" size="2">
| mallesons</font><font face="Tahoma"> </font><font face="Tahoma"
size="2">stephen</font><font face="Tahoma"> </font><font face="Tahoma"
size="2"> jaques</font><font face="Tahoma"><br>
</font><b><font face="Tahoma" size="2">T</font></b><font face="Tahoma"
size="2"> +61 (2) 9296 3668 |</font><b><font face="Tahoma"> </font><font
face="Tahoma" size="2"> F</font></b><font face="Tahoma" size="2"> +61
(2) 9296 3885 |</font><b><font face="Tahoma"> </font><font
face="Tahoma" size="2">M</font></b><font face="Tahoma" size="2"> +61
(408) 675 907</font><br>
<b><font face="Tahoma" size="2">E</font></b><font face="Tahoma" size="2">
<a href="http://links.10026.com/?link=mailto:mike.hodgson@.mallesons.nospam.com">
mailto:mike.hodgson@.mallesons.nospam.com</a> |</font><b><font
face="Tahoma"> </font><font face="Tahoma" size="2">W</font></b><font
face="Tahoma" size="2"> <a href="http://links.10026.com/?link=/">http://www.mallesons.com">
http://www.mallesons.com</a></font></span> </p>
</div>
<br>
<br>
Mango wrote:
<blockquote cite="miduqIMeBIGFHA.2180@.TK2MSFTNGP12.phx.gbl" type="cite">
<pre wrap="">HI friends,
I've got one question. When I realize "log in" in my sql server, I am using
SP like this:
CREATE Procedure CustomerLogin
(
@.Email nvarchar(30),
@.Pwd nvarchar(10),
@.CustomerID int OUTPUT
)
AS
SELECT
@.CustomerID = CustomerID
FROM
Customers
WHERE
Email = @.Email COLLATE SQL_Latin1_General_CP1_CS_AS
AND
Pwd =@.Pwd COLLATE SQL_Latin1_General_CP1_CS_AS
IF @.@.Rowcount < 1
SELECT
@.CustomerID = 0
GO
The problem is that if the password is "qweqwe" and I try to log in with
"qweqwe " or even "qweqwe " (I mean with space after last symbol) it
succeed!!!
Interesting but if I try to log in with " qweqwe" (I mean with space in
beginning) it not succeed.
I don't know why. Could you please somebody help me?
</pre>
</blockquote>
</body>
</html>
--020209070906080502050607--|||the datatype of Pwd is nvarchar. I found that is working corect if i write
it like this:
CREATE Procedure CustomerLogin
(
@.Email nvarchar(80),
@.Pwd nvarchar(50),
@.CustomerID int OUTPUT
)
AS
SELECT
@.CustomerID = CustomerID
FROM
Customers
WHERE
Email + '1' = @.Email COLLATE SQL_Latin1_General_CP1_CS_AS + '1'
AND
Pwd + '1'=@.Pwd COLLATE SQL_Latin1_General_CP1_CS_AS + '1'
IF @.@.Rowcount < 1
SELECT
@.CustomerID = 0
GO
But I am sure this is not the best approach
"Mike Hodgson" <mike.hodgson@.mallesons.nospam.com> wrote in message
news:#t9fdRIGFHA.2608@.TK2MSFTNGP10.phx.gbl...
> Post the DDL for your Customers table. Specifically, what's datatype of
> the Pwd column?
> --
> *mike hodgson* |/ database administrator/ | mallesons stephen jaques
> *T* +61 (2) 9296 3668 |* F* +61 (2) 9296 3885 |* M* +61 (408) 675 907
> *E* mailto:mike.hodgson@.mallesons.nospam.com |* W*
http://www.mallesons.com
>
> Mango wrote:
> >HI friends,
> >
> >I've got one question. When I realize "log in" in my sql server, I am
using
> >SP like this:
> >
> >CREATE Procedure CustomerLogin
> >
> >(
> >
> > @.Email nvarchar(30),
> >
> > @.Pwd nvarchar(10),
> >
> > @.CustomerID int OUTPUT
> >
> >)
> >
> >AS
> >
> >
> >
> >SELECT
> >
> > @.CustomerID = CustomerID
> >
> >
> >
> >FROM
> >
> > Customers
> >
> >
> >
> >WHERE
> >
> > Email = @.Email COLLATE SQL_Latin1_General_CP1_CS_AS
> >
> > AND
> >
> > Pwd =@.Pwd COLLATE SQL_Latin1_General_CP1_CS_AS
> >
> >
> >
> >IF @.@.Rowcount < 1
> >
> >SELECT
> >
> > @.CustomerID = 0
> >
> >GO
> >
> >
> >
> >The problem is that if the password is "qweqwe" and I try to log in with
> >"qweqwe " or even "qweqwe " (I mean with space after last symbol)
it
> >succeed!!!
> >
> >Interesting but if I try to log in with " qweqwe" (I mean with space in
> >beginning) it not succeed.
> >
> >I don't know why. Could you please somebody help me?
> >
> >
> >
> >
>

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.

problem with SP to return last @@Identity

I need to retun the last inserted Identity value. - The SP below has a synta
x
error on the Set line. How can I fix it?
create procedure stp_GetIdentity
@.e int output
as
SET NOCOUNT ON
Set @.e = Select @.@.Identity
return
go
Thanks,
Rich"Rich" <Rich@.discussions.microsoft.com> wrote in message
news:E3FF5947-5ED7-4E0A-BCD7-486D27C51375@.microsoft.com...
>I need to retun the last inserted Identity value. - The SP below has a
>syntax
> error on the Set line. How can I fix it?
> create procedure stp_GetIdentity
> @.e int output
> as
> SET NOCOUNT ON
> Set @.e = Select @.@.Identity
> return
> go
> Thanks,
> Rich
Set @.e = @.@.Identity
or
Select @.e = @.@.Identity
Option 1 is preferred for a single assignment.
Also look up scope_identity() in BOL.|||The offending line should be
SELECT @.e = @.@.IDENTITY
however, why create a stored procedure to get @.@.IDENTITY, when you can just
retrieve its value within a batch using SELECT @.@.IDENTITY?
"Rich" wrote:

> I need to retun the last inserted Identity value. - The SP below has a syn
tax
> error on the Set line. How can I fix it?
> create procedure stp_GetIdentity
> @.e int output
> as
> SET NOCOUNT ON
> Set @.e = Select @.@.Identity
> return
> go
> Thanks,
> Rich|||create procedure stp_GetIdentity
@.e int output
as
SET NOCOUNT ON
Select @.e = @.@.Identity
return
go
--This seems to work
"Rich" wrote:

> I need to retun the last inserted Identity value. - The SP below has a syn
tax
> error on the Set line. How can I fix it?
> create procedure stp_GetIdentity
> @.e int output
> as
> SET NOCOUNT ON
> Set @.e = Select @.@.Identity
> return
> go
> Thanks,
> Rich|||Thanks. From what I understand Scope_Identity works within a specified scop
e
which I interpret to mean if you insert a row into tbl1 which contains 10
rows in one procedure and also insert a row into tbl2 which contains 700 row
s
in another procedure and you only want to return the Identity value in tbl1
you could use Scope_Identity.
May I ask how Scope_Identity would be implemented in my SP to return the
Identity value of the last inserted row into tbl1?
?
"Raymond D'Anjou" wrote:

> "Rich" <Rich@.discussions.microsoft.com> wrote in message
> news:E3FF5947-5ED7-4E0A-BCD7-486D27C51375@.microsoft.com...
> Set @.e = @.@.Identity
> or
> Select @.e = @.@.Identity
> Option 1 is preferred for a single assignment.
> Also look up scope_identity() in BOL.
>
>|||"Rich" <Rich@.discussions.microsoft.com> wrote in message
news:6E159771-9CB3-45ED-95D1-7EF10E72DFFA@.microsoft.com...
> Thanks. From what I understand Scope_Identity works within a specified
> scope
> which I interpret to mean if you insert a row into tbl1 which contains 10
> rows in one procedure and also insert a row into tbl2 which contains 700
> rows
> in another procedure and you only want to return the Identity value in
> tbl1
> you could use Scope_Identity.
> May I ask how Scope_Identity would be implemented in my SP to return the
> Identity value of the last inserted row into tbl1?
>
set @.a = scope_identity()
scope_identity() has another advantage.
If you have a trigger on a table that inserts a row into another table with
an identity column.
@.@.identity in your stored procedure will return the ID of the last insert,
that is, the one in your trigger.
scope_identity() will return the ID you want.sql

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 sp and uniqueidentifier

Hi,

I use this procedure to add a record to the db (SQL 2005)
i constantly get this error:

Conversion failed when converting from a character string to uniqueidentifier.

This is the sp:

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go

ALTER PROC [dbo].[AddBootloader]

@.BootName nvarchar(50),
@.Version nvarchar(50),
@.CSD nvarchar(50),
@.CreatorID uniqueidentifier,
@.FilePath nvarchar(150),
@.FileSize nvarchar(150)

AS
INSERT INTO dbo.EB_Bootloaders

([Bootname]
,[Version]
,[CSD]
,[FilePath]
,[FileSize]
,[CreatorID])


VALUES

(
@.BootName,
@.Version,
@.CSD,
@.CreatorID,
@.FilePath,
@.FileSize)

And this is the table:

USE [Ebdata]
GO
/****** Object: Table [dbo].[EB_Bootloaders] Script Date: 07/12/2006 10:06:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[EB_Bootloaders](
[ID] [bigint] IDENTITY(1,3) NOT NULL,
[BootName] [nvarchar](50) COLLATE Latin1_General_CI_AS NULL,
[Version] [nvarchar](50) COLLATE Latin1_General_CI_AS NULL,
[CSD] [nvarchar](50) COLLATE Latin1_General_CI_AS NULL,
[FilePath] [nvarchar](150) COLLATE Latin1_General_CI_AS NULL,
[FileSize] [nvarchar](50) COLLATE Latin1_General_CI_AS NULL,
[CreateDate] [datetime] NULL CONSTRAINT [DF_EB_Bootloaders_CreateDate] DEFAULT (getdate()),
[CreatorID] [uniqueidentifier] NOT NULL,
[UpdateDate] [datetime] NULL,
[UpdateUser] [uniqueidentifier] NULL,
CONSTRAINT [PK_EB_Bootloaders_1] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]

GO
USE [Ebdata]
GO
ALTER TABLE [dbo].[EB_Bootloaders] WITH NOCHECK ADD CONSTRAINT [FK_EB_Bootloaders_aspnet_Users] FOREIGN KEY([CreatorID])
REFERENCES [dbo].[aspnet_Users] ([UserId])
NOT FOR REPLICATION
GO
ALTER TABLE [dbo].[EB_Bootloaders] WITH NOCHECK ADD CONSTRAINT [FK_EB_Bootloaders_aspnet_Users1] FOREIGN KEY([UpdateUser])
REFERENCES [dbo].[aspnet_Users] ([UserId])
NOT FOR REPLICATION

The funny thing is that i copied the sp code from another which runs perfect,
I insert a Guid from an asp.net page.

Hope someone can help me here because im am stucked!

Cheers WimmoHi Wimmo

Aren't your VALUES in your insert statement in the wrong order (@.CreatorID should be last not fourth)?|||set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go

ALTER PROC [dbo].[AddBootloader]

@.BootName nvarchar(50),
@.Version nvarchar(50),
@.CSD nvarchar(50),
@.CreatorID uniqueidentifier,
@.FilePath nvarchar(150),
@.FileSize nvarchar(150)

AS
INSERT INTO dbo.EB_Bootloaders

([Bootname]
,[Version]
,[CSD]
,[CreatorID]
,[FilePath]
,[FileSize]
)


VALUES

(
@.BootName,
@.Version,
@.CSD,
@.CreatorID,
@.FilePath,
@.FileSize)|||Euh thanx, think i was sleeping!
Glad some people are awake!
Thanx for helping me!

cheers Wim

Problem with SP

Hello All!
CREATE PROCEDURE dbo.PlbetII (@.UserID NvarChar(50),
@.Wager Nvarchar(50))
AS
IF EXISTS (SELECT 1 FROM Bankroll WHERE UserID=@.UserID)
begin
Update BankRoll
Set Wager = Wager + CAST(@.Wager as Nvarchar)
where userID = @.userID
return -1
end
ELSE
begin
Insert Bankroll (Wager) Values (@.Wager)
RETURN @.@.IDENTITY
end
GO
Having a little problem with the SP above. I'm trying to take a value from
the a "Wage" textbox, and update the value in the table. The userID number
is a value in the userID texbox, and already created in the SQL table. I
need to make sure the the wage value will go in the right row, where the use
r
ID matches. I get an error in SQL, "Server: Msg 515, Level 16, State 2,
Procedure PlbetII, Line 13
Cannot insert the value NULL into column 'UserID', table
'FootBet.dbo.Bankroll'; column does not allow nulls. INSERT fails.
The statement has been terminated.
The 'PlbetII' procedure attempted to return a status of NULL, which is not
allowed. A status of 0 will be returned instead."
I'm not sure why it's inserting the user ID. I see at "Set Wager = Wager +
CAST(@.Wager as Nvarchar)
where userID = @.userID" might be my problem, but I thought it's just
returning the value for user id and selecting it. I'm so .
Any help would be great!!!
TIA!!
RudyThe identity value (or autoincrement) for the column userId is not set,
hence the impossibility of inserting a new record at line 13 without
specifying the value for UserId. When creating a new record, you have two
choice: specify the value for UserId or ask SQL-Server to automatically
create a new value each time by setting the identity property.
From you piece of code, it's impossible to tell which one of these two
methods you should use.
Also, I'm not sure if the line Set Wager = Wager + CAST(@.Wager as
Nvarchar) will do what you are expecting it to do.
Sylvain Lafontaine, ing.
MVP - Technologies Virtual-PC
E-mail: http://cerbermail.com/?QugbLEWINF
"Rudy" <Rudy@.discussions.microsoft.com> wrote in message
news:B0D0D405-F131-4106-8602-E5F77D684B4D@.microsoft.com...
> Hello All!
> CREATE PROCEDURE dbo.PlbetII (@.UserID NvarChar(50),
> @.Wager Nvarchar(50))
> AS
> IF EXISTS (SELECT 1 FROM Bankroll WHERE UserID=@.UserID)
> begin
> Update BankRoll
> Set Wager = Wager + CAST(@.Wager as Nvarchar)
> where userID = @.userID
> return -1
> end
> ELSE
> begin
> Insert Bankroll (Wager) Values (@.Wager)
> RETURN @.@.IDENTITY
> end
> GO
> Having a little problem with the SP above. I'm trying to take a value
> from
> the a "Wage" textbox, and update the value in the table. The userID
> number
> is a value in the userID texbox, and already created in the SQL table. I
> need to make sure the the wage value will go in the right row, where the
> user
> ID matches. I get an error in SQL, "Server: Msg 515, Level 16, State 2,
> Procedure PlbetII, Line 13
> Cannot insert the value NULL into column 'UserID', table
> 'FootBet.dbo.Bankroll'; column does not allow nulls. INSERT fails.
> The statement has been terminated.
> The 'PlbetII' procedure attempted to return a status of NULL, which is not
> allowed. A status of 0 will be returned instead."
> I'm not sure why it's inserting the user ID. I see at "Set Wager = Wager
> +
> CAST(@.Wager as Nvarchar)
> where userID = @.userID" might be my problem, but I thought it's just
> returning the value for user id and selecting it. I'm so .
> Any help would be great!!!
> TIA!!
> Rudy
>
>|||Rudy (Rudy@.discussions.microsoft.com) writes:
> CREATE PROCEDURE dbo.PlbetII (@.UserID NvarChar(50),
> @.Wager Nvarchar(50))
> AS
> IF EXISTS (SELECT 1 FROM Bankroll WHERE UserID=@.UserID)
> begin
> Update BankRoll
> Set Wager = Wager + CAST(@.Wager as Nvarchar)
> where userID = @.userID
> return -1
> end
> ELSE
> begin
> Insert Bankroll (Wager) Values (@.Wager)
> RETURN @.@.IDENTITY
> end
> GO
> Having a little problem with the SP above. I'm trying to take a value
> from the a "Wage" textbox, and update the value in the table. The
> userID number is a value in the userID texbox, and already created in
> the SQL table. I need to make sure the the wage value will go in the
> right row, where the user ID matches. I get an error in SQL,
> "Server: Msg 515, Level 16, State 2, Procedure PlbetII, Line 13
> Cannot insert the value NULL into column 'UserID', table
> 'FootBet.dbo.Bankroll'; column does not allow nulls. INSERT fails.
> The statement has been terminated.
> The 'PlbetII' procedure attempted to return a status of NULL, which is not
> allowed. A status of 0 will be returned instead."
> I'm not sure why it's inserting the user ID.
Obviously the table does not have the IDENTITY property. If I am to
believe your procedure, the UserID column is nvarchar(50), why IDENTITY
is completely off-track.
Just say:
Insert Bankroll (UserID, Wager) Values (@.UserID, @.Wager)
By the way, the RETURN statement is mainly used to indicate
success/failure, with success being 0 and anything else means an
error. The regular way to return a value is to use an OUTPUT
parameter.
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pr...oads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodin...ions/books.mspx|||Thank you Erland and Sylvain!
I did change things up a little bit per you sugestions. Still having
problems, but I suspect something with the table itself. I deleted the table
,
and built it again, and now it works fine.
Thanks again!
Rudy
"Erland Sommarskog" wrote:

> Rudy (Rudy@.discussions.microsoft.com) writes:
> Obviously the table does not have the IDENTITY property. If I am to
> believe your procedure, the UserID column is nvarchar(50), why IDENTITY
> is completely off-track.
> Just say:
> Insert Bankroll (UserID, Wager) Values (@.UserID, @.Wager)
> By the way, the RETURN statement is mainly used to indicate
> success/failure, with success being 0 and anything else means an
> error. The regular way to return a value is to use an OUTPUT
> parameter.
> --
> Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
> Books Online for SQL Server 2005 at
> http://www.microsoft.com/technet/pr...oads/books.mspx
> Books Online for SQL Server 2000 at
> http://www.microsoft.com/sql/prodin...ions/books.mspx
>|||Can run the following query and post the output.
select COLUMNPROPERTY( object_id('Bankroll') , 'pub_id' , 'AllowsNull' ) as
nullable,
COLUMNPROPERTY( object_id('Bankroll') , 'userID' , 'IsIdentity' ) as
[autogenID]
And a few observations:
Why is UserID nvarchar?
and why do you do this step?
Wager + CAST(@.Wager as Nvarchar)
when @.wager is already nvarchar.. and are you trying to append the string
wager or add the wager to the existing value? Is Wager a numeric value or ha
s
characters like the dollar and pounds.
It will be better to answer your question if you give table definition and
test data
so that we can reproduce the error here.

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