Showing posts with label procedure. Show all posts
Showing posts with label procedure. Show all posts

Friday, March 30, 2012

Problem running stored procedure inside another store procedure

hi,

I want to use a stored procedure inside a stored procedure simulteanously changing the database.
this is my base store procedure

alter PROCEDURE create_file @.dbname sysname
AS
declare @.fname varchar(30)
declare @.fsizes nvarchar
BEGIN
DECLARE @.cmd varchar(1000)
set @.cmd = 'osql -E -d ' + @.dbname + ' -Q "exec ret_sizes @.fname OUTPUT,@.fsizes OUTPUT"'
exec master..xp_cmdshell @.cmd
END

if i execute the his "exec create_file ertis"
i get error as

Msg 137, Level 15, State 2, Server HCC-BPVHD1, Line 1
Must declare the variable '@.fname'.
NULL

the procedure called inside the mail procedure is

alter procedure ret_sizes
@.fname varchar(30) OUTPUT,
@.fsizes nvarchar OUTPUT
as
begin
select @.fname=name, @.fsizes=size from sysfiles
order by fileid
end

Please help meThe @.Cmd string doesn't seem to include the second exec.

set @.cmd = 'osql -E -d ' + @.dbname + ' + '-Q' + ' "exec ret_sizes @.fname OUTPUT,@.fsizes OUTPUT"' '

exec @.CMD

__________________________________________________ ___________

Quote:

Originally Posted by eRTIS SQL

hi,

I want to use a stored procedure inside a stored procedure simulteanously changing the database.
this is my base store procedure

alter PROCEDURE create_file @.dbname sysname
AS
declare @.fname varchar(30)
declare @.fsizes nvarchar
BEGIN
DECLARE @.cmd varchar(1000)
set @.cmd = 'osql -E -d ' + @.dbname + ' -Q "exec ret_sizes @.fname OUTPUT,@.fsizes OUTPUT"'
exec master..xp_cmdshell @.cmd
END

if i execute the his "exec create_file ertis"
i get error as

Msg 137, Level 15, State 2, Server HCC-BPVHD1, Line 1
Must declare the variable '@.fname'.
NULL

the procedure called inside the mail procedure is

alter procedure ret_sizes
@.fname varchar(30) OUTPUT,
@.fsizes nvarchar OUTPUT
as
begin
select @.fname=name, @.fsizes=size from sysfiles
order by fileid
end

Please help me

sql

Problem running stored Procedure

Hi Guys & Gals

I'm having problems running a stored procedure, I'm getting an error that I don't understand. My procedure is this:


ALTER PROC sp_get_allowed_growers
@.GrowerList varchar(500)
AS
BEGIN
SET NOCOUNT ON

DECLARE @.SQL varchar(600)

SET @.SQL =
'SELECT nu_code, nu_description, nu_master
FROM nursery WHERE nu_master IN (' + @.GrowerList + ') ORDER BY nu_code ASC'

EXEC(@.SQL)
END
GO

and the code I'm using to execute the procedure is this:


public DataSet GetGrowers(string Username)
{
System.Text.StringBuilder UserRoles = new System.Text.StringBuilder();
UsersDB ps = new UsersDB();
SqlDataReader dr = ps.GetRolesByUser(Username);
while(dr.Read())
{
UserRoles.Append(dr["RoleName"]+",");
}
UserRoles.Remove(UserRoles.Length-1,1);
//Create instance of Connection and Command objects
SqlConnection transloadConnection = new SqlConnection(ConfigurationSettings.AppSettings["connectionStringTARPS"]);
SqlDataAdapter transloadCommand = new SqlDataAdapter("sp_get_allowed_growers",transloadConnection);
//Create and fill the DataSet
SqlParameter paramList = new SqlParameter("@.GrowerList",SqlDbType.VarChar);
paramList.Value = UserRoles.ToString();
transloadCommand.SelectCommand.Parameters.Add(paramList);
DataSet dsGrowers = new DataSet();
transloadCommand.Fill(dsGrowers);
return dsGrowers;

}

The UserRoles stringbuilder has an appropriate value when it is passed to the stored procedure. When I run the stored procedure in query analyser it runs just fine. However, when I step through the code above, I get the following error:


Line 1: Incorrect syntax near 'sp_get_allowed_growers'.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Data.SqlClient.SqlException: Line 1: Incorrect syntax near 'sp_get_allowed_growers'.

Anyone with any ideas would be very helpful...Try surrounding your parameter list (just the one parameter) in your stored procedure in parentheses. Also, I've never used Alter proc, I use Create Procedure (not to say that Alter proc doesn't work, I don't know - just an observation)|||CREATE PROCEDURE dbo.sp_get_allowed_growers
(
@.GrowerList varchar(500)
)
AS

I always use dbo.sp"NAME" because when you push to production your account may or may not be the dbo.|||Although, technically, you should never preface your stored procedure names with sp_. sp_ is used by sql server to designate system stored procedures. When you preface your own sprocs with sp_, you cause sql server to first search through all system sprocs, then through the local sprocs to find your procedure. In other words, you're adding in a bit of inefficiency to each and every procedure call.|||Thanks for the suggestions guys, I tried that and I still get the same error. It's a bit of an odd one because the stored procedure seems fine. I compiled it in query analyser and I can run it in query analyser by right-clicking and selecting "Open", I'm then prompted for the paramter and it returns the expected result so, as far as I know, it's functioning correctly. When I step through the code calling the procedure, the Autos window shows the value of the parameter as "'Admins','NH'" which is exactly what I'd expect.

I'm pretty sure it's something to do with the way that the value of the parameter is being assigned. In query analyser, when I run the stored proc and I am prompted for the value of the @.GrowerList parameter, I have to type the values in exactly like this 'Admins','NH' and it works.

The odd thing is that the database is raising the error and saying that there's a syntax error in the stored proc when there definitely isn't. It would be different if it was raising a type conversion error but it isn't.

Keep thinking folks, I'll send a small prize to whoever can help me crack it (don't get too excited, it will probably be a company pen or something!)

Cheers,|||Add

transloadCommand.SelectCommand.CommandType=CommandType.StoredProcedure;

before you call .Fill()

And I would also concur that naming an sp with an sp_ prefix will slow things down...|||Thanks doug, that cracked it straight away, I'm very grateful. If you email me your address to imacleverbloke@.mcowan.info I'll pop the freebies in the post. Don't get too excited but they're worth having!

As for the sp_ naming convention, I hear about that performance issue too late and I'm kinda stuck with it until the next comprehensive overhaul.

Cheers guys.

problem running sp_addpublication

When I am running sp_addpublication, I am getting the following error. Whats
wrong?
I was able to run the same script before and this stored procedure was
running fine.
Server: Msg 14294, Level 16, State 1, Procedure sp_verify_job_identifiers,
Line 24
Supply either @.job_id or @.job_name to identify the job.
Job 'Server_Name\InstanceNanme-DBName-1' started successfully.
Adam,
I suggest running profiler to see what are the parameters being sent to this
procedure and to debug where the process is going wrong. The most likely
cause is a changed servername, as the error is raised in several system
procedures and the code is usually of the form...
select @.distribution_jobid = job_id from msdb..sysjobs_view where
name = @.name and
UPPER(originating_server) = UPPER(CONVERT(sysname,
SERVERPROPERTY('ServerName')))
if @.distribution_jobid IS NULL
begin
-- Message from msdb.dbo.sp_verify_job_identifiers
RAISERROR(14262, -1, -1, 'Job', @.name)
GOTO UNDO
end
So, if your servername has changed, this could be the cause of the problem.
In this case:
Use Master
go
Select @.@.Servername
This should return your current server name but if it
returns NULL then try:
Use Master
go
Sp_DropServer 'OldName'
GO
Use Master
go
Sp_Addserver 'NewName', 'local'
GO
Stop and Start SQL Services
Cheers,
Paul Ibison SQL Server MVP, www.replicationanswers.com
(recommended sql server 2000 replication book:
http://www.nwsu.com/0974973602p.html)
|||Thank you Paul for your response. Your solution does make sense, however in
my case the server name has not changed. I had forgotten to run the script to
create jobs, running it seems to have solve the problem. I am pasting a part
of that script to give you the idea.
if (select count(*) from msdb.dbo.syscategories where name =
N'REPL-LogReader') < 1
execute msdb.dbo.sp_add_category N'REPL-LogReader'
Thanks.
-A
"Paul Ibison" wrote:

> Adam,
> I suggest running profiler to see what are the parameters being sent to this
> procedure and to debug where the process is going wrong. The most likely
> cause is a changed servername, as the error is raised in several system
> procedures and the code is usually of the form...
> select @.distribution_jobid = job_id from msdb..sysjobs_view where
> name = @.name and
> UPPER(originating_server) = UPPER(CONVERT(sysname,
> SERVERPROPERTY('ServerName')))
> if @.distribution_jobid IS NULL
> begin
> -- Message from msdb.dbo.sp_verify_job_identifiers
> RAISERROR(14262, -1, -1, 'Job', @.name)
> GOTO UNDO
> end
> So, if your servername has changed, this could be the cause of the problem.
> In this case:
> Use Master
> go
> Select @.@.Servername
> This should return your current server name but if it
> returns NULL then try:
> Use Master
> go
> Sp_DropServer 'OldName'
> GO
> Use Master
> go
> Sp_Addserver 'NewName', 'local'
> GO
> Stop and Start SQL Services
> Cheers,
> Paul Ibison SQL Server MVP, www.replicationanswers.com
> (recommended sql server 2000 replication book:
> http://www.nwsu.com/0974973602p.html)
>
>
|||Hi Adam,
I do have the same issue like while buidling my replication using
scripts it is giving the following error
Server: Msg 14294, Level 16, State 1, Procedure sp_verify_job_identifiers,
Line 24
Supply either @.job_id or @.job_name to identify the job
even if I have created the job for 'REPL-LogReader', before creating
publication it is throwing the same error, is there any way that I can solve
this error.
Please help.
Thanks
Ramesh
"Adam" wrote:
[vbcol=seagreen]
> Thank you Paul for your response. Your solution does make sense, however in
> my case the server name has not changed. I had forgotten to run the script to
> create jobs, running it seems to have solve the problem. I am pasting a part
> of that script to give you the idea.
> if (select count(*) from msdb.dbo.syscategories where name =
> N'REPL-LogReader') < 1
> execute msdb.dbo.sp_add_category N'REPL-LogReader'
> Thanks.
> -A
> "Paul Ibison" wrote:

Problem running Proc from Job

I have a stored procedure that runs fine using the Query Analyzer:

exec sp_ProcessRecords

However, when I create a job to run the stored proc once an hour, the job fails, with the following message:

Executed as user: sa. String or binary data would be truncated. [SQLSTATE 22001] (Error 8152) The statement has been terminated. [SQLSTATE 01000] (Error 3621). The step failed.

I don't think it's a permission problem, since the job runs as sa.

I don't understand why it would work if I run it manually, but not when it runs as a job.

Any help would be greatly appreciated.Check your parameters that are being passed to the stored procedure. This means that some parameter that is being passed it too long for the datatype and will be truncated.|||Originally posted by rnealejr
Check your parameters that are being passed to the stored procedure. This means that some parameter that is being passed it too long for the datatype and will be truncated.

Unfortunately, the stored proc called from the job does not take any parameters.

The odd thing is that the stored proc will work fine if it is run manually from the Query Analyzer. The error only occurs when the proc is run from the job, using the exact syntax!

I'm at a loss...|||Can you post the stored proc code - or describe what it is doing ? If you are doing inserts/updates then the same problem can occur.sql

Problem returning two values from stored procedures

Hi, i am trying to return two values from SQL 2000 using a single stored procedure. The stored working fine in Query Analyser and returns the two values and two grids in the results window.

My problem is that when i execute the stored procedure using ADO.Net the dataset only has one of the values. e.g TId : 2, where it should read 'TId' : 2, 'ConfigPath': 'C:\blah'

Please could anyone shed ligth on this problem?

here the code for the stored procedure:

CREATE PROCEDURE dbo.GetTillInfo
(
@.TillIdR varchar(50),
@.Password varchar(50)
)
AS

declare @.TillId int
declare @.configpath varchar(150)

IF Exists (SELECT Id FROM Tills WHERE TillRef=@.TillId and TillPassword=@.Password)
BEGIN

set @.TillIdR = (SELECT Id FROM Tills WHERE TillRef=@.TillId and TillPassword=@.Password)
select @.TillIdR as 'TId'

set @.configpath = (SELECT configpath from customer,tills where
tills.customerid = customer.id and tills.id = @.login)
select @.configpath as 'ConfigPath'
END
ELSE
BEGIN
set @.TillIdR = 0
select @.TillIdR as 'TId'
set @.configpath =''
select @.configpath as 'ConfigPath'
END
GOOff the top of my head, the two results may be returned but in two tables as you are performing two selects.

To get round this you could change your select query to return the two values like:-


IF ...
set @.TillIdR = (SELECT Id FROM Tills WHERE TillRef=@.TillId and TillPassword=@.Password)
set @.configpath = (SELECT configpath from customer,tills where
tills.customerid = customer.id and tills.id = @.login)

select @.TillIdR as 'TId', @.configpath as 'ConfigPath'
END
ELSE
BEGIN
set @.TillIdR = 0
set @.configpath =''
select @.TillIdR as 'TId', @.configpath as 'ConfigPath'
END
GO

This is off the top of my head at work - you may have to play with the stored proc.

Rob

Problem returning OUTPUT in stored procedure

Hi, I have this output, @.RegisterFlag int OUTPUT

and I have a transaction going on, so my code (I just put some relevant code here) is:

1BEGIN TRAN2 SELECT @.getDealername = OrgNameFROM OrgWHERE OrgName = @.DealerName3If @.getDealernameisnull45ELSE6 BEGIN7 set @.RegisterFlag = 28ROLLBACK TRAN9 RETURN10 END1112COMMIT TRAN13set @.RegisterFlag = 1

The problem I am facing now is I couldn't get @.RegisterFlag = 2 return back to my asp.net code when it reached line 7, instead I got this error mesg:

Transaction count after EXECUTE indicates that a COMMIT or ROLLBACK TRANSACTION statement is missing. Previous count = 1, current count = 0.

How do I fix this? Many big thanks.

Hi, it's ok already. I realize that the problem is I have both transaction code, one in asp.net and another one in stored procedure. After taken out the one in asp.net, it works now. Thanks.

Wednesday, March 28, 2012

Problem returning data

I have a stored procedure (in SQL Server 2005 Express) that returns a string. The problem is when I call it from my web page I get only the first character of the string. This is my SP:

ALTER PROCEDURE

dbo.usp_CalcDeliveryCharge

@.mintDistance

int,

@.mintCustomer_ID

int= 0,

@.mintRate

int= 0OUTPUT,

@.mstrZone

nchar(10) =null OUTPUT

AS

/* SET NOCOUNT ON */SELECT@.mintRate=RATE,

@.mstrZone=ZONE

FROMtblRatesWHERECustomer_ID=@.mintCustomer_IDANDMile_Range_Min <= @.mintDistanceANDMile_Range_Max >= @.mintDistance

And this is my code:

sql_Command.CommandText =

"usp_CalcDeliveryCharge"

sql_Command.CommandType = CommandType.StoredProcedure

sql_Command.Parameters.Clear()

sql_Command.Parameters.AddWithValue(

"@.mintDistance", intApproxMiles)

sql_Command.Parameters.AddWithValue(

"@.mintCustomer_ID", Profile.CompanyID)

sql_Conn.Open()

sql_Reader = sql_Command.ExecuteReader()

While (sql_Reader.Read())Me.lblZone.Text = sql_Reader.Item(0).ToStringEndWhile

sql_Conn.Close()

sql_Reader.Close()

sql_Command.Dispose()

If you are using OUTPUT parameters you need to add the output parameters in the asp.net code also and set their direction as output and retrieve the values through those parameters not through datareader.
checkthis article if it helps.

Problem report xp_MSADEnabled

Hello,
I have detected a problem with the stored procedure xp_MSADEnabled. I am using Windows 2000 (workstation, 5.00.2195, SP4) and SQLServer 2000 Developer (Product version 8.00.858 SP3). Calling xp_MSADEnabled results in an unspecified error (-2147467259).
If I call the same procedure on a Windows 2003 Server machine, it works fine.
This procedure is called in several other system procedures like sp_addmergepublication and sp_dropmergepublication.
I am developing the replication functionality of a database application. I discovered the problem when I wanted to call sp_addmergepublication from my ADO.NET application. This resulted in the SqlException "A severe error occurred on the current command.
The results, if any, should be discarded". Calling this procedure from the SQL Query Analyzer did not result in the error.
greeting, Marco
Hi
Looking at other people having problems with this xp_MSADEnabled tend to
point to service account problems such as duplicate account entries in the
AD or insufficient permissions to access it.
John
"Marco Broenink" <marco.broenink@.ict.nl> wrote in message
news:0EB1A879-F364-4646-AE5B-28C3754194AD@.microsoft.com...
> Hello,
> I have detected a problem with the stored procedure xp_MSADEnabled. I am
using Windows 2000 (workstation, 5.00.2195, SP4) and SQLServer 2000
Developer (Product version 8.00.858 SP3). Calling xp_MSADEnabled results in
an unspecified error (-2147467259).
> If I call the same procedure on a Windows 2003 Server machine, it works
fine.
> This procedure is called in several other system procedures like
sp_addmergepublication and sp_dropmergepublication.
> I am developing the replication functionality of a database application. I
discovered the problem when I wanted to call sp_addmergepublication from my
ADO.NET application. This resulted in the SqlException "A severe error
occurred on the current command. The results, if any, should be discarded".
Calling this procedure from the SQL Query Analyzer did not result in the
error.
> greeting, Marco

Problem report xp_MSADEnabled

Hello
I have detected a problem with the stored procedure xp_MSADEnabled. I am using Windows 2000 (workstation, 5.00.2195, SP4) and SQLServer 2000 Developer (Product version 8.00.858 SP3). Calling xp_MSADEnabled results in an unspecified error (-2147467259)
If I call the same procedure on a Windows 2003 Server machine, it works fine
This procedure is called in several other system procedures like sp_addmergepublication and sp_dropmergepublication.
I am developing the replication functionality of a database application. I discovered the problem when I wanted to call sp_addmergepublication from my ADO.NET application. This resulted in the SqlException "A severe error occurred on the current command. The results, if any, should be discarded". Calling this procedure from the SQL Query Analyzer did not result in the error
greeting, MarcoHi
Looking at other people having problems with this xp_MSADEnabled tend to
point to service account problems such as duplicate account entries in the
AD or insufficient permissions to access it.
John
"Marco Broenink" <marco.broenink@.ict.nl> wrote in message
news:0EB1A879-F364-4646-AE5B-28C3754194AD@.microsoft.com...
> Hello,
> I have detected a problem with the stored procedure xp_MSADEnabled. I am
using Windows 2000 (workstation, 5.00.2195, SP4) and SQLServer 2000
Developer (Product version 8.00.858 SP3). Calling xp_MSADEnabled results in
an unspecified error (-2147467259).
> If I call the same procedure on a Windows 2003 Server machine, it works
fine.
> This procedure is called in several other system procedures like
sp_addmergepublication and sp_dropmergepublication.
> I am developing the replication functionality of a database application. I
discovered the problem when I wanted to call sp_addmergepublication from my
ADO.NET application. This resulted in the SqlException "A severe error
occurred on the current command. The results, if any, should be discarded".
Calling this procedure from the SQL Query Analyzer did not result in the
error.
> greeting, Marcosql

Problem report xp_MSADEnabled

Hello,
I have detected a problem with the stored procedure xp_MSADEnabled. I am using Windows 2000 (workstation, 5.00.2195, SP4) and SQLServer 2000 Developer (Product version 8.00.858 SP3). Calling xp_MSADEnabled results in an unspecified error (-2147467259).
If I call the same procedure on a Windows 2003 Server machine, it works fine.
This procedure is called in several other system procedures like sp_addmergepublication and sp_dropmergepublication.
I am developing the replication functionality of a database application. I discovered the problem when I wanted to call sp_addmergepublication from my ADO.NET application. This resulted in the SqlException "A severe error occurred on the current command.
The results, if any, should be discarded". Calling this procedure from the SQL Query Analyzer did not result in the error.
greeting, Marco
This procedure test to see if the particular SQL Server is Active Directory enabled.
In your code are you publishing your publication to Active Directory? IE in the proc sp_addpublication are you setting
@.add_to_active_directory to true?
Do you need this functionality?
Looking for a SQL Server replication book?
http://www.nwsu.com/0974973602.html
|||Thanks for reply.
I don't need active directory functionality. I set the @.add_to_active_directory to false but the sp_addmergepublication still calls xp_MSADEnabled.
-- Hilary Cotter wrote: --
This procedure test to see if the particular SQL Server is Active Directory enabled.
In your code are you publishing your publication to Active Directory? IE in the proc sp_addpublication are you setting
@.add_to_active_directory to true?
Do you need this functionality?
Looking for a SQL Server replication book?
http://www.nwsu.com/0974973602.html
|||Hi
Looking at other people having problems with this xp_MSADEnabled tend to
point to service account problems such as duplicate account entries in the
AD or insufficient permissions to access it.
John
"Marco Broenink" <marco.broenink@.ict.nl> wrote in message
news:0EB1A879-F364-4646-AE5B-28C3754194AD@.microsoft.com...
> Hello,
> I have detected a problem with the stored procedure xp_MSADEnabled. I am
using Windows 2000 (workstation, 5.00.2195, SP4) and SQLServer 2000
Developer (Product version 8.00.858 SP3). Calling xp_MSADEnabled results in
an unspecified error (-2147467259).
> If I call the same procedure on a Windows 2003 Server machine, it works
fine.
> This procedure is called in several other system procedures like
sp_addmergepublication and sp_dropmergepublication.
> I am developing the replication functionality of a database application. I
discovered the problem when I wanted to call sp_addmergepublication from my
ADO.NET application. This resulted in the SqlException "A severe error
occurred on the current command. The results, if any, should be discarded".
Calling this procedure from the SQL Query Analyzer did not result in the
error.
> greeting, Marco

Monday, March 26, 2012

PROBLEM REGARDING VARIABLE PASSING TO STORED PROCEDURE

Hi

I am WORKING IN AN APPLICATION USING SQL SERVER 2000 AND VB6

I'VE A PROBLEM REGARDING VARIABLE PASSING TO STORED PROCEDURE

I WILL EXPLAIN WITH AN EXAMPLE

TABLE STRUCTURE

AccAccounts

Accid(Numeric) AccName(Varchar)

-

1 Cash A/c

2 Students A/c

3 HDFC Bank A/c

my Application will pass the "Accid" as a string format to Stored Procedure

STORED PROCEDURE

--

CREATE PROCEDURE GetAccName
@.Accid Varchar(100)
AS
Select * from Accaccount where accid in (@.Accid)

when i run this SP

declare @.Accid Varchar(100)
set @.Accid ='1,2'

exec GetAccName @.Accid

i get the following error

Server: Msg 8114, Level 16, State 5, Procedure GetAccName, Line 4
Error converting data type varchar to numeric.

please "ANY ONE" help me!!.

The above example is only an example

REGARDS

JAMES

Hi,

You can not use the @.Variable which holds the multiple accountids in Static SQL statement.. you need to use dynamic sql..

Code Snippet

CREATE PROCEDURE GetAccName
@.Accid Varchar(100)
AS
Declare @.cmd varchar(4000)

Set @.Cmd = 'Select * from Accaccount where accid in (' + @.Accid')'

exec (@.cmd)

But would suggest you to go through the following link to see the advantages and disadvantages..

http://www.sommarskog.se/dynamic_sql.html

Regards,

|||

You can also do this without dynamic sql.

Code Snippet

CREATE PROCEDURE GetAccName
@.Accid Varchar(100)
AS
Select *
from AccAccounts
where charindex(','+convert(varchar,accid)+',',','+@.Accid+',')>0

|||

THANK U VERY MUCH

|||

Hi James

You shouldn't pass comma separated values to the stored procedure, like: '1,2,3' . Because when you call the sproc it is trying to convert your value(because accid is numeric in your table) to varchar implicitly and due to the ',' in your data the conversion is going to fail and throws an error. You need to write some other logic to get it done.

Thanks & Regards,

Kiran.Y

|||

HI

THX FOR REPLY

WHAT IN CASE IF I NEED A QRY

Select * from AccAccounts where Accid Not in (1,2)

|||

>0 means a match is found

=0 means no match.

Code Snippet

CREATE PROCEDURE GetAccName
@.Accid Varchar(100)
AS
Select *
from AccAccounts
where charindex(','+convert(varchar,accid)+',',','+@.Accid+',') = 0

|||

Thx

Problem referencing a global temporary table

I'm having difficulty referencing a global temporary table in a stored procedure. My stored procedure will execute correctly for days on end, but then all of a sudden it will stop working and I will get messages like:

Invalid object name '##TableName'.

and

Cannot drop the table '##TableName, because it does not exist in the system catalog.

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

In my stored procedure I am first creating my temporary table using the syntax below. I need to create a seed value from a parameter, so that is why I am using the SET @.SQL and EXEC(@.SQL) statements:

SET @.SQL =
'CREATE TABLE ##TableName (
[Value1] [varchar] (11) ,
[Value2] [numeric](13, 0) ,
[Value3] [varchar] (30) ,
[Value4] [varchar] (30) ,
[Value5] [int] IDENTITY (' + CAST(@.Variable AS VARCHAR(10)) + ', 1) NOT NULL )'
EXEC(@.SQL)

I then begin a transaction and perform an INSERT INTO statement into this temp table, and then later perform a SELECT statement, and finally a DROP statement.

Any ideas or can anyone point me in the right direction as to why this works SOME of the time?

Just top make sure that you know that a global temporary table can be only at one time per server. So if any other users also executes the procedure and drops the "global" temporary table, it won′t be accessible in the other session anymore. Temp Table with one dash '#' are session specific, so can created in every session. Global ones, with two dashes '##' are global created. Every user sees them and can manipulate (or even drop) them.

So I guess any other process dropped your global temporary table.

HTH, jens Suessmeyer.

http://www.sqlserver2005.de
|||Thank you for the info. I am aware of the difference between the global-specific temp table vs. the session-specific temp table. In fact, I chose to create the global-specific temp table so that I can reference the table after the EXEC(@.SQL) statement runs.
|||

It is hard to tell what might be wrong with the code without seeing some sort of repro script. Note that if there are multiple references to a global temporary table for example, SQL Server will delete it automatically after all users referencing the table have disconnected from the server. This can lead to unpredictable behavior if you use multiple connections but doesn't seem to be the case here. In any case, you can modify the code to use just a temporary table instead by doing following:

create table #.... (

columns except the identity column

)

exec ('alter table # add ... identity column with seed')

insert into #...

select * from #...

This approach doesn't require any dynamic SQL except for the few DDLs and it is easier to read/debug also.

|||

hi!

i used some temporary table in store procedure (sqlserver 2005)

our team have report software calisto .

the calisto use crystal and reports which use

this store procedure .

because of that,

we have list of many temporary table with the same name

#dbo.sug_name ... ,#dbo.sug_name ... ,......

in the system database .

what could be the reason for that and how can we drop it ?

Msg 3701, Level 11, State 5, Line 2

Cannot drop the table '#sug_name', because it does not exist or you do not have permission."

Problem referencing a global temporary table

I'm having difficulty referencing a global temporary table in a stored procedure. My stored procedure will execute correctly for days on end, but then all of a sudden it will stop working and I will get messages like:

Invalid object name '##TableName'.

and

Cannot drop the table '##TableName, because it does not exist in the system catalog.

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

In my stored procedure I am first creating my temporary table using the syntax below. I need to create a seed value from a parameter, so that is why I am using the SET @.SQL and EXEC(@.SQL) statements:

SET @.SQL =
'CREATE TABLE ##TableName (
[Value1] [varchar] (11) ,
[Value2] [numeric](13, 0) ,
[Value3] [varchar] (30) ,
[Value4] [varchar] (30) ,
[Value5] [int] IDENTITY (' + CAST(@.Variable AS VARCHAR(10)) + ', 1) NOT NULL )'
EXEC(@.SQL)

I then begin a transaction and perform an INSERT INTO statement into this temp table, and then later perform a SELECT statement, and finally a DROP statement.

Any ideas or can anyone point me in the right direction as to why this works SOME of the time?

Just top make sure that you know that a global temporary table can be only at one time per server. So if any other users also executes the procedure and drops the "global" temporary table, it won′t be accessible in the other session anymore. Temp Table with one dash '#' are session specific, so can created in every session. Global ones, with two dashes '##' are global created. Every user sees them and can manipulate (or even drop) them.

So I guess any other process dropped your global temporary table.

HTH, jens Suessmeyer.

http://www.sqlserver2005.de|||Thank you for the info. I am aware of the difference between the global-specific temp table vs. the session-specific temp table. In fact, I chose to create the global-specific temp table so that I can reference the table after the EXEC(@.SQL) statement runs.|||

It is hard to tell what might be wrong with the code without seeing some sort of repro script. Note that if there are multiple references to a global temporary table for example, SQL Server will delete it automatically after all users referencing the table have disconnected from the server. This can lead to unpredictable behavior if you use multiple connections but doesn't seem to be the case here. In any case, you can modify the code to use just a temporary table instead by doing following:

create table #.... (

columns except the identity column

)

exec ('alter table # add ... identity column with seed')

insert into #...

select * from #...

This approach doesn't require any dynamic SQL except for the few DDLs and it is easier to read/debug also.

|||

hi!

i used some temporary table in store procedure (sqlserver 2005)

our team have report software calisto .

the calisto use crystal and reports which use

this store procedure .

because of that,

we have list of many temporary table with the same name

#dbo.sug_name ... ,#dbo.sug_name ... ,......

in the system database .

what could be the reason for that and how can we drop it ?

Msg 3701, Level 11, State 5, Line 2

Cannot drop the table '#sug_name', because it does not exist or you do not have permission."

Wednesday, March 21, 2012

Problem passing variables as parameters to extended stored procedure

Hello all,

I have written an XP for SQL Server 2000 SP2. It performs as expected if I call the XP with literal values for the parameters, however when I wrap the XP call into a regular stored procedure, only the first character of each input string is seen by the XP! Here are the relevant code snippets:

C++ Extended Stored Procedure:

(Basically all this code is doing is retrieving the parameters and printing them back out)

srv_paraminfo(srvproc, 1, &bType, &uMaxLen, &uLen, NULL, &bNull);

param1 = new BYTE[uLen + 1];

srv_paraminfo(srvproc, 1, &bType, &uMaxLen, &uLen, param1, &bNull);

param1[uLen] = '\0';

srv_paraminfo(srvproc, 2, &bType, &uMaxLen, &uLen, NULL, &bNull);

param2 = new BYTE[uLen + 1];

srv_paraminfo(srvproc, 2, &bType, &uMaxLen, &uLen, param2, &bNull);

param2[uLen] = '\0';

srv_paraminfo(srvproc, 3, &bType, &uMaxLen, &uLen, NULL, &bNull);

param3 = new BYTE[uLen + 1];

srv_paraminfo(srvproc, 3, &bType, &uMaxLen, &uLen, param3, &bNull);

param3[uLen] = '\0';

sprintf(msgText, "Params received by xp: %s, %s, %s", param1, param2, param3);

srv_sendmsg( srvproc, SRV_MSG_ERROR, 0,(DBTINYINT)0, (DBTINYINT)0,NULL,0,0,msgText,SRV_NULLTERM);

srv_senddone(srvproc, SRV_DONE_ERROR, (DBUSMALLINT)0, (DBINT)0);

Calling the XP with literal values:

EXEC xp_mytest 'one','two','three'

Output:

Params received by xp: one, two, three

Calling XP via a stored procedure:

create procedure sp_mytest

(

@.myvar1 nvarchar(200),

@.myvar2 nvarchar(50),

@.myvar3 nvarchar(50)

)

as BEGIN

PRINT @.myvar1

PRINT @.myvar2

PRINT @.myvar3

EXEC xp_mytest @.myvar1, @.myvar2, @.myvar3

END

EXEC sp_mytest 'one','two','three'

Output:

one

two

three

Params received by xp: o,t,t

Any insight or assistance is greatly appreciated!!!

Your definition of sp_mytest implies that its input parameters are not unicode. The first 0 character implies end-of-string. You pass unicode parameters to it from within sp_mytest (you declare them as nvarchar), and these characters are 2-byte with second byte zero, that's why you get back only the first character from the string.

Either change your sp_mytest definition to use varchar instead of nvarchar, or your xp_mytest definition to use wchar instead of char.

Problem passing variables as parameters to extended stored procedure

Hello all,

I have written an XP for SQL Server 2000 SP2. It performs as expected if I call the XP with literal values for the parameters, however when I wrap the XP call into a regular stored procedure, only the first character of each input string is seen by the XP! Here are the relevant code snippets:

C++ Extended Stored Procedure:

(Basically all this code is doing is retrieving the parameters and printing them back out)

srv_paraminfo(srvproc, 1, &bType, &uMaxLen, &uLen, NULL, &bNull);

param1 = new BYTE[uLen + 1];

srv_paraminfo(srvproc, 1, &bType, &uMaxLen, &uLen, param1, &bNull);

param1[uLen] = '\0';

srv_paraminfo(srvproc, 2, &bType, &uMaxLen, &uLen, NULL, &bNull);

param2 = new BYTE[uLen + 1];

srv_paraminfo(srvproc, 2, &bType, &uMaxLen, &uLen, param2, &bNull);

param2[uLen] = '\0';

srv_paraminfo(srvproc, 3, &bType, &uMaxLen, &uLen, NULL, &bNull);

param3 = new BYTE[uLen + 1];

srv_paraminfo(srvproc, 3, &bType, &uMaxLen, &uLen, param3, &bNull);

param3[uLen] = '\0';

sprintf(msgText, "Params received by xp: %s, %s, %s", param1, param2, param3);

srv_sendmsg( srvproc, SRV_MSG_ERROR, 0,(DBTINYINT)0, (DBTINYINT)0,NULL,0,0,msgText,SRV_NULLTERM);

srv_senddone(srvproc, SRV_DONE_ERROR, (DBUSMALLINT)0, (DBINT)0);

Calling the XP with literal values:

EXECxp_mytest 'one','two','three'

Output:

Params received by xp: one, two, three

Calling XP via a stored procedure:

create procedure sp_mytest

(

@.myvar1 nvarchar(200),

@.myvar2 nvarchar(50),

@.myvar3 nvarchar(50)

)

as BEGIN

PRINT @.myvar1

PRINT @.myvar2

PRINT @.myvar3

EXECxp_mytest @.myvar1, @.myvar2, @.myvar3

END

EXEC sp_mytest 'one','two','three'

Output:

one

two

three

Params received by xp: o,t,t

Any insight or assistance is greatly appreciated!!!

Your definition of sp_mytest implies that its input parameters are not unicode. The first 0 character implies end-of-string. You pass unicode parameters to it from within sp_mytest (you declare them as nvarchar), and these characters are 2-byte with second byte zero, that's why you get back only the first character from the string.

Either change your sp_mytest definition to use varchar instead of nvarchar, or your xp_mytest definition to use wchar instead of char.

Problem passing columns as parameter!

Dear friens,

I need to pass a column as a parameter in my query. I did this:

ALTER PROCEDURE [dbo].[GD_SP_GET_UsersByDIR_COD]

@.Direccao nvarchar(11),

@.prmFieldName nvarchar(25),

@.prmFieldValue nvarchar(25)

AS

BEGIN

IF @.prmFieldValue='*' OR @.prmFieldValue=''

BEGIN

SELECT TOP (100) PERCENT dbo.ADServico_User.UserID, dbo.ADUser.UserName AS Nome, dbo.HARDWARE.New_Computername AS Computername,

dbo.ModeloPC.MOD_ModeloPC AS ModeloPC, dbo.Monitor.MON_Monitor AS Monitor, dbo.Status.StatusNome AS Status,

dbo.HARDWARE.Migrada AS Interven??o, dbo.HARDWARE.MigraViaChange AS [Migrada via Change], dbo.HARDWARE.StatusID,

dbo.HARDWARE.NS_ID

FROM dbo.ModeloPC INNER JOIN

dbo.SERVICO INNER JOIN

dbo.ADServico_User ON dbo.SERVICO.S_GrupoServico = dbo.ADServico_User.GrupoServico INNER JOIN

dbo.HARDWARE ON dbo.ADServico_User.UserID = dbo.HARDWARE.UserID INNER JOIN

dbo.Status ON dbo.HARDWARE.StatusID = dbo.Status.ID ON dbo.ModeloPC.MODELO_ID = dbo.HARDWARE.MODELO_ID INNER JOIN

dbo.Monitor ON dbo.HARDWARE.MONITOR_ID = dbo.Monitor.MONITOR_ID INNER JOIN

dbo.DIRECCAO ON dbo.SERVICO.S_NomeDir = dbo.DIRECCAO.DIR_COD LEFT OUTER JOIN

dbo.ADUser ON dbo.HARDWARE.UserID = dbo.ADUser.UserID

WHERE (dbo.HARDWARE.StatusID <> 6) AND (dbo.DIRECCAO.DIR_COD = @.Direccao)

ORDER BY Nome

END

ELSE

BEGIN

DECLARE @.SQL varchar(7000)

SET @.Direccao='CGD-DAS'

SET @.prmFieldName='UserID'

SET @.prmFieldValue='C095122'

SET @.SQL = 'SELECT

TOP (100) PERCENT dbo.ADServico_User.UserID, dbo.ADUser.UserName AS Nome, dbo.HARDWARE.New_Computername AS Computername,

dbo.ModeloPC.MOD_ModeloPC AS ModeloPC, dbo.Monitor.MON_Monitor AS Monitor, dbo.Status.StatusNome AS Status,

dbo.HARDWARE.Migrada AS Interven??o, dbo.HARDWARE.MigraViaChange AS [Migrada via Change], dbo.HARDWARE.StatusID,

dbo.HARDWARE.NS_ID

FROM dbo.ModeloPC INNER JOIN

dbo.SERVICO INNER JOIN

dbo.ADServico_User ON dbo.SERVICO.S_GrupoServico = dbo.ADServico_User.GrupoServico INNER JOIN

dbo.HARDWARE ON dbo.ADServico_User.UserID = dbo.HARDWARE.UserID INNER JOIN

dbo.Status ON dbo.HARDWARE.StatusID = dbo.Status.ID ON dbo.ModeloPC.MODELO_ID = dbo.HARDWARE.MODELO_ID INNER JOIN

dbo.Monitor ON dbo.HARDWARE.MONITOR_ID = dbo.Monitor.MONITOR_ID INNER JOIN

dbo.DIRECCAO ON dbo.SERVICO.S_NomeDir = dbo.DIRECCAO.DIR_COD LEFT OUTER JOIN

dbo.ADUser ON dbo.HARDWARE.UserID = dbo.ADUser.UserID

WHERE (dbo.HARDWARE.StatusID <> 6) AND (dbo.DIRECCAO.DIR_COD = @.Direccao)

AND '+ @.prmFieldName +' =' + @.prmFieldValue + ' '

EXEC @.SQL

END

END

THE COMAND EXECUTE SUCESSFULLY IN QUERY ANALISER, BUT IN ASP.NET 2.0 CLIENT RETURNS THE FOLLOWING ERROR:

Server Error in '/WS_GestaoDesktop' Application.


The name 'SELECT
TOP (100) PERCENT dbo.ADServico_User.UserID, dbo.ADUser.UserName AS Nome, dbo.HARDWARE.New_Computername AS Computername,
dbo.ModeloPC.MOD_ModeloPC AS ModeloPC, dbo.Monitor.MON_Monitor AS Monitor, dbo.Status.StatusNome AS Status,
dbo.HARDWARE.Migrada AS Interven??o, dbo.HARDWARE.MigraViaChange AS [Migrada via Change], dbo.HARDWARE.StatusID,
dbo.HARDWARE.NS_ID
FROM dbo.ModeloPC INNER JOIN
dbo.SERVICO INNER JOIN
dbo.ADServico_User ON dbo.SERVICO.S_GrupoServico = dbo.ADServico_User.GrupoServico INNER JOIN
dbo.HARDWARE ON dbo.ADServico_User.UserID = dbo.H' is not a valid identifier.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Data.SqlClient.SqlException: The name 'SELECT
TOP (100) PERCENT dbo.ADServico_User.UserID, dbo.ADUser.UserName AS Nome, dbo.HARDWARE.New_Computername AS Computername,
dbo.ModeloPC.MOD_ModeloPC AS ModeloPC, dbo.Monitor.MON_Monitor AS Monitor, dbo.Status.StatusNome AS Status,
dbo.HARDWARE.Migrada AS Interven??o, dbo.HARDWARE.MigraViaChange AS [Migrada via Change], dbo.HARDWARE.StatusID,
dbo.HARDWARE.NS_ID
FROM dbo.ModeloPC INNER JOIN
dbo.SERVICO INNER JOIN
dbo.ADServico_User ON dbo.SERVICO.S_GrupoServico = dbo.ADServico_User.GrupoServico INNER JOIN
dbo.HARDWARE ON dbo.ADServico_User.UserID = dbo.H' is not a valid identifier.

Source Error:

Line 3269: }

Line 3270: dsHardware.dtGD_SP_GET_UsersByDIR_CODDataTable dataTable = new dsHardware.dtGD_SP_GET_UsersByDIR_CODDataTable();

Line 3271: this.Adapter.Fill(dataTable);

Line 3272: return dataTable;

Line 3273: }

The problem is based here:

WHERE (dbo.HARDWARE.StatusID <> 6) AND (dbo.DIRECCAO.DIR_COD = @.Direccao)

if you want to pass a static value use

WHERE (dbo.HARDWARE.StatusID <> 6) AND (dbo.DIRECCAO.DIR_COD = ''' + @.Direccao + ''')

if you want to pass a identifier use

WHERE (dbo.HARDWARE.StatusID <> 6) AND (dbo.DIRECCAO.DIR_COD = ' + @.Direccao + ')

HTh, Jens K. Suessmeyer.

http://www.sqlserver2005.de

|||

Dear Friend,I changed as you told, but the error still there! :-(

CREATE PROCEDURE [dbo].[GD_SP_GET_UsersByDIR_COD]

@.Direccao nvarchar(11),

@.prmFieldName nvarchar(25),

@.prmFieldValue nvarchar(25)

AS

BEGIN

IF @.prmFieldValue='*' OR @.prmFieldValue=''

BEGIN

SELECT TOP (100) PERCENT dbo.ADServico_User.UserID, dbo.ADUser.UserName AS Nome, dbo.HARDWARE.New_Computername AS Computername,

dbo.ModeloPC.MOD_ModeloPC AS ModeloPC, dbo.Monitor.MON_Monitor AS Monitor, dbo.Status.StatusNome AS Status,

dbo.HARDWARE.Migrada AS Interven??o, dbo.HARDWARE.MigraViaChange AS [Migrada via Change], dbo.HARDWARE.StatusID,

dbo.HARDWARE.NS_ID

FROM dbo.ModeloPC INNER JOIN

dbo.SERVICO INNER JOIN

dbo.ADServico_User ON dbo.SERVICO.S_GrupoServico = dbo.ADServico_User.GrupoServico INNER JOIN

dbo.HARDWARE ON dbo.ADServico_User.UserID = dbo.HARDWARE.UserID INNER JOIN

dbo.Status ON dbo.HARDWARE.StatusID = dbo.Status.ID ON dbo.ModeloPC.MODELO_ID = dbo.HARDWARE.MODELO_ID INNER JOIN

dbo.Monitor ON dbo.HARDWARE.MONITOR_ID = dbo.Monitor.MONITOR_ID INNER JOIN

dbo.DIRECCAO ON dbo.SERVICO.S_NomeDir = dbo.DIRECCAO.DIR_COD LEFT OUTER JOIN

dbo.ADUser ON dbo.HARDWARE.UserID = dbo.ADUser.UserID

WHERE (dbo.HARDWARE.StatusID <> 6) AND (dbo.DIRECCAO.DIR_COD = @.Direccao)

ORDER BY Nome

END

ELSE

BEGIN

DECLARE @.SQL varchar(7000)

SET @.Direccao='CGD-DAS'

SET @.prmFieldName='UserID'

SET @.prmFieldValue='C095122'

SET @.SQL = 'SELECT

TOP (100) PERCENT dbo.ADServico_User.UserID, dbo.ADUser.UserName, dbo.HARDWARE.New_Computername,

dbo.ModeloPC.MOD_ModeloPC, dbo.Monitor.MON_Monitor AS Monitor, dbo.Status.StatusNome,

dbo.HARDWARE.Migrada, dbo.HARDWARE.MigraViaChange, dbo.HARDWARE.StatusID,

dbo.HARDWARE.NS_ID

FROM dbo.ModeloPC INNER JOIN

dbo.SERVICO INNER JOIN

dbo.ADServico_User ON dbo.SERVICO.S_GrupoServico = dbo.ADServico_User.GrupoServico INNER JOIN

dbo.HARDWARE ON dbo.ADServico_User.UserID = dbo.HARDWARE.UserID INNER JOIN

dbo.Status ON dbo.HARDWARE.StatusID = dbo.Status.ID ON dbo.ModeloPC.MODELO_ID = dbo.HARDWARE.MODELO_ID INNER JOIN

dbo.Monitor ON dbo.HARDWARE.MONITOR_ID = dbo.Monitor.MONITOR_ID INNER JOIN

dbo.DIRECCAO ON dbo.SERVICO.S_NomeDir = dbo.DIRECCAO.DIR_COD LEFT OUTER JOIN

dbo.ADUser ON dbo.HARDWARE.UserID = dbo.ADUser.UserID

WHERE (dbo.HARDWARE.StatusID <> 6) AND (dbo.DIRECCAO.DIR_COD ='+ @.Direccao +')

AND '+ @.prmFieldName +' =' + @.prmFieldValue + ' '

EXEC @.SQL

END

END

ERROR:

Msg 203, Level 16, State 2, Procedure GD_SP_GET_UsersByDIR_COD, Line 49

The name 'SELECT

TOP (100) PERCENT dbo.ADServico_User.UserID, dbo.ADUser.UserName AS Nome, dbo.HARDWARE.New_Computername AS Computername,

dbo.ModeloPC.MOD_ModeloPC AS ModeloPC, dbo.Monitor.MON_Monitor AS Monitor, dbo.Status.StatusNome AS Status,

dbo.HARDWARE.Migrada AS Interven??o, dbo.HARDWARE.MigraViaChange AS [Migrada via Change], dbo.HARDWARE.StatusID,

dbo.HARDWARE.NS_ID

FROM dbo.ModeloPC INNER JOIN

dbo.SERVICO INNER JOIN

dbo.ADServico_User ON dbo.SERVICO.S_GrupoServico = dbo.ADServico_User.GrupoServico INNER JOIN

dbo.HARDWARE ON dbo.ADServico_User.UserID = dbo.H' is not a valid identifier.

|||

change the following things..

CREATE PROCEDURE [dbo].[GD_SP_GET_UsersByDIR_COD]

@.Direccao nvarchar(11),

@.prmFieldName nvarchar(25),

@.prmFieldValue nvarchar(25)

AS

BEGIN

IF @.prmFieldValue='*' OR @.prmFieldValue=''

BEGIN

SELECT TOP (100) PERCENT dbo.ADServico_User.UserID, dbo.ADUser.UserName AS Nome, dbo.HARDWARE.New_Computername AS Computername,

dbo.ModeloPC.MOD_ModeloPC AS ModeloPC, dbo.Monitor.MON_Monitor AS Monitor, dbo.Status.StatusNome AS Status,

dbo.HARDWARE.Migrada AS Interven??o, dbo.HARDWARE.MigraViaChange AS [Migrada via Change], dbo.HARDWARE.StatusID,

dbo.HARDWARE.NS_ID

FROM dbo.ModeloPC INNER JOIN

dbo.SERVICO INNER JOIN

dbo.ADServico_User ON dbo.SERVICO.S_GrupoServico = dbo.ADServico_User.GrupoServico INNER JOIN

dbo.HARDWARE ON dbo.ADServico_User.UserID = dbo.HARDWARE.UserID INNER JOIN

dbo.Status ON dbo.HARDWARE.StatusID = dbo.Status.ID ON dbo.ModeloPC.MODELO_ID = dbo.HARDWARE.MODELO_ID INNER JOIN

dbo.Monitor ON dbo.HARDWARE.MONITOR_ID = dbo.Monitor.MONITOR_ID INNER JOIN

dbo.DIRECCAO ON dbo.SERVICO.S_NomeDir = dbo.DIRECCAO.DIR_COD LEFT OUTER JOIN

dbo.ADUser ON dbo.HARDWARE.UserID = dbo.ADUser.UserID

WHERE (dbo.HARDWARE.StatusID <> 6) AND (dbo.DIRECCAO.DIR_COD = @.Direccao)

ORDER BY Nome

END

ELSE

BEGIN

DECLARE @.SQL varchar(7000)

SET @.Direccao='CGD-DAS'

SET @.prmFieldName='UserID'

SET @.prmFieldValue='C095122'

SET @.SQL = 'SELECT

TOP (100) PERCENT dbo.ADServico_User.UserID, dbo.ADUser.UserName, dbo.HARDWARE.New_Computername,

dbo.ModeloPC.MOD_ModeloPC, dbo.Monitor.MON_Monitor AS Monitor, dbo.Status.StatusNome,

dbo.HARDWARE.Migrada, dbo.HARDWARE.MigraViaChange, dbo.HARDWARE.StatusID,

dbo.HARDWARE.NS_ID

FROM dbo.ModeloPC INNER JOIN

dbo.SERVICO INNER JOIN

dbo.ADServico_User ON dbo.SERVICO.S_GrupoServico = dbo.ADServico_User.GrupoServico INNER JOIN

dbo.HARDWARE ON dbo.ADServico_User.UserID = dbo.HARDWARE.UserID INNER JOIN

dbo.Status ON dbo.HARDWARE.StatusID = dbo.Status.ID ON dbo.ModeloPC.MODELO_ID = dbo.HARDWARE.MODELO_ID INNER JOIN

dbo.Monitor ON dbo.HARDWARE.MONITOR_ID = dbo.Monitor.MONITOR_ID INNER JOIN

dbo.DIRECCAO ON dbo.SERVICO.S_NomeDir = dbo.DIRECCAO.DIR_COD LEFT OUTER JOIN

dbo.ADUser ON dbo.HARDWARE.UserID = dbo.ADUser.UserID

WHERE (dbo.HARDWARE.StatusID <> 6) AND (dbo.DIRECCAO.DIR_COD ='''+ @.Direccao +''')

AND '+ @.prmFieldName +' =''' + @.prmFieldValue + ''' '

EXEC @.SQL

END

END

|||

Manid,

I changed as you told, but the error still there! :-(

Regards.

|||I guess you are either trying to change another procedure than you are executing or you will have to provide the whole snippet of code via mail or something to make it reproducable.

HTH, Jens K. Suessmeyer.

http://www.sqlserver2005.de|||

Dear Jens,

I created a more simple query, based in the same problem:

CREATE PROCEDURE TEMP

AS

DECLARE @.SQL varchar(8000)

DECLARE @.prmFieldName varchar(20)

DECLARE @.prmFieldValue varchar(20)

SET @.prmFieldName='UserID'

SET @.prmFieldValue='C095122'

SET @.SQL = 'SELECT New_Computername

FROM HARDWARE

WHERE '+ @.prmFieldName +' =''' + @.prmFieldValue + ''' '

EXEC @.SQL

The logical is the some of other queries, but in this one I can't executed it, because returns the following error:

Msg 2812, Level 16, State 62, Procedure TEMP, Line 15

Could not find stored procedure 'SELECT New_Computername

FROM HARDWARE

WHERE UserID ='C095122' '.

(1 row(s) affected)

If you can put this query with column parameter workink good, my problem probably is resolved for the other queries.

Thanks!

|||Sorry and blame on me for not seeing this, you will have to wriite the exec as follows:

EXEC(@.SQL)

HTH, jens K. Suessmeyer.

http://www.sqlserver2005.de|||

Dear friends,

I created a new simple query to try to resolve the problem of passing a column as parameter, using sp_executesql, but still return error. :-(

ALTER PROCEDURE TEMP

@.prmFieldName nvarchar(25),

@.prmFieldValue nvarchar(25)

AS

DECLARE @.SQL varchar(8000)

SET @.prmFieldName='UserID'

SET @.prmFieldValue='C095122'

SET @.SQL = N'SELECT New_Computername

FROM HARDWARE

WHERE '+ @.prmFieldName +' =''' + @.prmFieldValue + ''' '

EXECUTE sp_executesql @.SQL;

ERROR:

Msg 214, Level 16, State 2, Procedure sp_executesql, Line 1

Procedure expects parameter '@.statement' of type 'ntext/nchar/nvarchar'.

|||

Dear Friends,

I found the solution for my problem.

I must use EXECTUTE sp_executesql @.SQL in spite of EXEC @.SQL, and I must use nvarchar(4000) in spite of varchar(8000).

The final Result:

ALTER PROCEDURE [dbo].[GD_SP_GET_UsersByDIR_COD]

@.Direccao nvarchar(11),

@.prmFieldName nvarchar(30),

@.prmFieldValue nvarchar(25)

AS

BEGIN

IF @.prmFieldValue='*' OR @.prmFieldValue=''

BEGIN

SELECT TOP (100) PERCENT dbo.ADServico_User.UserID, dbo.ADUser.UserName AS Nome, dbo.HARDWARE.New_Computername AS Computername,

dbo.ModeloPC.MOD_ModeloPC AS ModeloPC, dbo.Monitor.MON_Monitor AS Monitor, dbo.Status.StatusNome AS Status,

dbo.HARDWARE.Migrada AS Interven??o, dbo.HARDWARE.MigraViaChange AS [Migrada via Change], dbo.HARDWARE.StatusID,

dbo.HARDWARE.NS_ID

FROM dbo.ModeloPC INNER JOIN

dbo.SERVICO INNER JOIN

dbo.ADServico_User ON dbo.SERVICO.S_GrupoServico = dbo.ADServico_User.GrupoServico INNER JOIN

dbo.HARDWARE ON dbo.ADServico_User.UserID = dbo.HARDWARE.UserID INNER JOIN

dbo.Status ON dbo.HARDWARE.StatusID = dbo.Status.ID ON dbo.ModeloPC.MODELO_ID = dbo.HARDWARE.MODELO_ID INNER JOIN

dbo.Monitor ON dbo.HARDWARE.MONITOR_ID = dbo.Monitor.MONITOR_ID INNER JOIN

dbo.DIRECCAO ON dbo.SERVICO.S_NomeDir = dbo.DIRECCAO.DIR_COD LEFT OUTER JOIN

dbo.ADUser ON dbo.HARDWARE.UserID = dbo.ADUser.UserID

WHERE (dbo.HARDWARE.StatusID <> 6) AND (dbo.DIRECCAO.DIR_COD = @.Direccao)

ORDER BY Nome

END

ELSE

BEGIN

DECLARE @.SQL nvarchar(4000)

SET @.SQL = N'SELECT

TOP (100) PERCENT dbo.ADServico_User.UserID, dbo.ADUser.UserName AS Nome, dbo.HARDWARE.New_Computername AS Computername,

dbo.ModeloPC.MOD_ModeloPC AS ModeloPC, dbo.Monitor.MON_Monitor AS Monitor, dbo.Status.StatusNome AS Status,

dbo.HARDWARE.Migrada AS Interven??o, dbo.HARDWARE.MigraViaChange AS [Migrada via Change], dbo.HARDWARE.StatusID,

dbo.HARDWARE.NS_ID

FROM dbo.ModeloPC INNER JOIN

dbo.SERVICO INNER JOIN

dbo.ADServico_User ON dbo.SERVICO.S_GrupoServico = dbo.ADServico_User.GrupoServico INNER JOIN

dbo.HARDWARE ON dbo.ADServico_User.UserID = dbo.HARDWARE.UserID INNER JOIN

dbo.Status ON dbo.HARDWARE.StatusID = dbo.Status.ID ON dbo.ModeloPC.MODELO_ID = dbo.HARDWARE.MODELO_ID INNER JOIN

dbo.Monitor ON dbo.HARDWARE.MONITOR_ID = dbo.Monitor.MONITOR_ID INNER JOIN

dbo.DIRECCAO ON dbo.SERVICO.S_NomeDir = dbo.DIRECCAO.DIR_COD LEFT OUTER JOIN

dbo.ADUser ON dbo.HARDWARE.UserID = dbo.ADUser.UserID

WHERE (dbo.HARDWARE.StatusID <> 6) AND (dbo.DIRECCAO.DIR_COD ='''+ @.Direccao +''')

AND '+ @.prmFieldName +' =''' + @.prmFieldValue + ''' '

EXECUTE sp_executesql @.SQL

END

END

THANKS FOR ALL YOUR IMPORTANT SUPPORT!!!

Problem passing a variable into a table-valued function

Hi,

i am encountering a problem in a stored procedure when a pass a variable value into a table-valued function. The table-valued function is named getCurrentDriver and has 1 attribute: car-ID.

The syntax is as follows:

select car.id, car.licenceNumber, car.brand, car.model,
(select driverName from getCurrentDriver(car.id)) as driverName
from car

When I try to compile I get following error on the line of the function:
Incorrect syntax near '.'

The database version is SQL Server 2000 SP3.

What am I doing wrong? Is there a workaround for this error?select car.id, car.licenceNumber, car.brand, car.model,
dbo.getCurrentDriver(car.id) as driverName
from car|||[sniped]

select car.id, car.licenceNumber, car.brand, car.model,
, dbo.getCurrentDriver(car.id) as driverName
from car

??|||The problem is that he is putting a table-valued function in the select clause. This is not allowed:

select car.id,
car.licenceNumber,
car.brand,
car.model,
(select driverName
from getCurrentDriver(car.id)) as driverName
from car

TBP, you need to JOIN to the results of a table function as if it were a table or a view:
Post the code for getCurrentDriver(), and we can help you out. Maybe you should be using a scalar function instead...|||dote. had'nt thought about that.|||also, part of the problem is that "license" is spelled wrong ;)|||Good eye. That would certainly not get past SQL Server 2005's Spell Checker.|||The problem is that he is putting a table-valued function in the select clause. This is not allowed:

select car.id,
car.licenceNumber,
car.brand,
car.model,
(select driverName
from getCurrentDriver(car.id)) as driverName
from car

TBP, you need to JOIN to the results of a table function as if it were a table or a view:
Post the code for getCurrentDriver(), and we can help you out. Maybe you should be using a scalar function instead...

Hi Blindman,
are you sure you can't use table-defined function in a select clause?
The syntax works when I do this:

declare @.CarID int
select @.CarID = 123

select car.id,
car.licenseNumber,
car.brand,
car.model,
(select driverName
from getCurrentDriver(@.CarID)) as driverName
from car
where car.id = @.CarID

The function getCurrentDriver is very straightforward and is tested successfully.
It seems to be a bug in SQL Server 2000 but I'm not sure...|||Good eye. That would certainly not get past SQL Server 2005's Spell Checker.
It's certainly fun trying to write SQL for tables whose columns are called "identifer" and "sirname"|||Hi Blindman,
are you sure you can't use table-defined function in a select clause?
The syntax works when I do this:

declare @.CarID int
select @.CarID = 123

select car.id,
car.licenseNumber,
car.brand,
car.model,
(select driverName
from getCurrentDriver(@.CarID)) as driverName
from car
where car.id = @.CarID

The function getCurrentDriver is very straightforward and is tested successfully.
It seems to be a bug in SQL Server 2000 but I'm not sure...
What do you expect to happen if your table function returns more than one record or more than one column? And if it always returns one record and one column, then it is a scalar function and should be defined as such.|||Hasn't this something to do with the missing schema name (owner in SQL 2000) when calling the function? Althought it beats me why the @.CarID example seems to work.

select car.id,
car.licenceNumber,
car.brand,
car.model,
(select driverName
from dbo.getCurrentDriver(car.id)) as driverName
from carsql

Problem ovewriting xp_sendmail

I am trying to overwrite xp_sendmail by a transact sql stored procedure. I delete the original one and write a new one with the same name but I keep receiving errors which seems to relate to the orinal one as if the security is kept in place even though I deleted the extended procedure.

Here are the details of what I did:

I created a stored procedure xp_sendmail in master database.

I called the procedure and receives the following error message:

Msg 15281, Level 16, State 1, Procedure xp_sendmail, Line 1

SQL Server blocked access to procedure 'sys.xp_sendmail' of component 'SQL Mail XPs' because this component is turned off as part of the security configuration for this server. A system administrator can enable the use of 'SQL Mail XPs' by using sp_configure. For more information about enabling 'SQL Mail XPs', see "Surface Area Configuration" in SQL Server Books Online.

I tried deleting the extended stored procedure with the same name from the visual interface of "Microsoft ssql server management studio". The process did not work, I received the following message: "Cannot use SP_DROPEXTENDEDPROC or DBCC DROPEXTENDEDPROC with xp_sendmail because "xp_sendmail" is a procedure. Use DROP PROCEDURE (MSSQL ERROR 3751)"

I believe the interface does not do the distinction between my procedure and the orinal extended procedure. I therefore tried the following:

drop the stored procedure I wrote.

drop once more the extended procedure. I received a different message: "Cannot drop procedure because it does not exists or you do not have the permission (mssql error 3701)"

I do refresh, I reopen the management studio, no matter, the extended procedure is still there. Only way I find to delete it from the interface is recreating from transact sql before redropping it.

sp_addextendedproc 'xp_sendmail', [the path of the dll here]

Even aftter doing all those and recreating my own procedure, I still see the extended procedure reapearing in the sql server management studio interface and I still receive the security error.

It is as if sql server fails to notice I dropped the procedure.

I am trying all those with the sa user so I doubt the issue comes from the fact that I lack permission.

Is there something that can be done to force sql server to consider my procedure as a separate one that the original one. Why is the extended procedure still appearing and why do I still receive security error after I drop it. I tried calling the procedure without with both the extended procedure and transact sql stored procedure dropped or with the extended one droped and the other one present, still I get no success and still receive the security error. I even tried freeing the dll from memory but it makes no difference:

DBCC xp_sendmail (free)

Thanks for the help.

I am really sorry to say this, but unfortunately this is an unsupported scenario and we will not be able to help.

My only recommendation at this point is to try to backup any important data from your system, and reinstall SQL Server. Once you have a clean system, create your XP under a different name (i.e. xp_sendmail2)

I strongly recommend using only the supported mechanisms designed to extend the system (such as creating new XPs, CLR assemblies, etc.) instead of trying to modify the system objects.

Thanks,

-Raul Garcia

SDE/T

SQL Server Engine

|||

Thanks for your time.

the reason we try to do this is because we have a bunch of application calling xp_sendmail and want to move to a mail sending method which allows to to define the smtp server address to enforce an email policy.

It is therefore easier to just overwrite the xp_sendmail than to overwrite all our applications to call another procedure. This used to work in sql server 2000.

That said, I don't think it is necessary to rebuild the server. I can run sp_addextendedproc to rerister the dll and it works. All I need to find is how to tell sql server to forget that this extended procedure existed. Even if it is deleted, it is still visible in the management studio interface and my procedure gets mixed up with the extended procedure when it comes to permission and settings.

If this cannot be achieved, I'll move to plan B. However, if anybody knows of a method to resolve this issue, then it would be appreciated.

Thanks again.

Tuesday, March 20, 2012

Problem on scripting stored procedures

I have tried to script all of stored procedures in one database on SQL server
2005 then it seems like get stacked. To script one stored procedure has no
problem however when try to script all stored procedures SSMS never respond.
I have never experience this problem on SQL server 2000.
Any help?
M. Matsuda (MMatsuda@.discussions.microsoft.com) writes:
> I have tried to script all of stored procedures in one database on SQL
> server 2005 then it seems like get stacked. To script one stored
> procedure has no problem however when try to script all stored
> procedures SSMS never respond.
> I have never experience this problem on SQL server 2000.
> Any help?
How many procedures are there in the database? There were performance
issues during the beta, but it appears to behave decently now.
One possibility is blocking, if someone has submitted:
BEGIN TRANSACTION
go
CREATE PROCEDURE ...
and never committed the transaction. You can use sp_who to determine if
you have any blocking in the database. If there is a non-zero value in
the Blk column, in means that the spid in Blk blocks the spid on that
line.
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/prodtechnol/sql/2005/downloads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodinfo/previousversions/books.mspx
|||There are 193 stored procedures and same process on SQL 2000 ends less than
30 second. There is no other user using SQL 2005 except myself. (Because this
SQL 2005 is used as application development purpose.)
When script one stored procedure SSMS promptly responded and showed dialog
where to save however when select all stored procedures it did not show the
dialog more than 10 minits.
Performance monitor showed 100% processor time during being stalled.
"Erland Sommarskog" wrote:

> M. Matsuda (MMatsuda@.discussions.microsoft.com) writes:
> How many procedures are there in the database? There were performance
> issues during the beta, but it appears to behave decently now.
> One possibility is blocking, if someone has submitted:
> BEGIN TRANSACTION
> go
> CREATE PROCEDURE ...
> and never committed the transaction. You can use sp_who to determine if
> you have any blocking in the database. If there is a non-zero value in
> the Blk column, in means that the spid in Blk blocks the spid on that
> line.
>
> --
> Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
> Books Online for SQL Server 2005 at
> http://www.microsoft.com/technet/prodtechnol/sql/2005/downloads/books.mspx
> Books Online for SQL Server 2000 at
> http://www.microsoft.com/sql/prodinfo/previousversions/books.mspx
>
|||M. Matsuda (MMatsuda@.discussions.microsoft.com) writes:
> There are 193 stored procedures
That's not an extraordiary lot.

> There is no other user using SQL 2005 except myself.
That does not preclude blocking, if that is what you were thinking.

> When script one stored procedure SSMS promptly responded and showed
> dialog where to save however when select all stored procedures it did
> not show the dialog more than 10 minits.
> Performance monitor showed 100% processor time during being stalled.
Hm, is Mgmt Studio and SQL Server on the same machine? How much memory
is there in the box? How much memory does SQL Server actually have?
What I have noticed with SQL 2005 is that if it falls down 30-35 MB in
memory, the simplest queries can take over 10 seconds.
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/prodtechnol/sql/2005/downloads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodinfo/previousversions/books.mspx
|||SQL 2005 installed in Netfinity 5000 with 896MB RAM (P3 500M HZ) + Windows
2003 Server. SSMS and SQL 2005 reside on same machine.
Before upgrade to SQL 2005, SQL 2000 run on same machine did not have any
problem. Even SQL 2000 + Windows XP installed on notebook (Think pad 512MB
RAM) + Visual Stuido 2005 run on same time does not have any problem to
perform this process.
"Erland Sommarskog" wrote:

> M. Matsuda (MMatsuda@.discussions.microsoft.com) writes:
> That's not an extraordiary lot.
>
> That does not preclude blocking, if that is what you were thinking.
>
> Hm, is Mgmt Studio and SQL Server on the same machine? How much memory
> is there in the box? How much memory does SQL Server actually have?
> What I have noticed with SQL 2005 is that if it falls down 30-35 MB in
> memory, the simplest queries can take over 10 seconds.
> --
> Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
> Books Online for SQL Server 2005 at
> http://www.microsoft.com/technet/prodtechnol/sql/2005/downloads/books.mspx
> Books Online for SQL Server 2000 at
> http://www.microsoft.com/sql/prodinfo/previousversions/books.mspx
>
|||I don't know how you can get 896MB of memory, I suspect it is really 512MB.
But in any case you are not meeting the minimum hardware requirements on CPU
for SQL2005 let alone the recommended. As such I would expect it to be
somewhat slow.
http://www.microsoft.com/sql/editions/developer/sysreqs.mspx
Andrew J. Kelly SQL MVP
"M. Matsuda" <MMatsuda@.discussions.microsoft.com> wrote in message
news:A207A819-2286-4552-9EE4-3F4918687303@.microsoft.com...[vbcol=seagreen]
> SQL 2005 installed in Netfinity 5000 with 896MB RAM (P3 500M HZ) +
> Windows
> 2003 Server. SSMS and SQL 2005 reside on same machine.
> Before upgrade to SQL 2005, SQL 2000 run on same machine did not have any
> problem. Even SQL 2000 + Windows XP installed on notebook (Think pad 512MB
> RAM) + Visual Stuido 2005 run on same time does not have any problem to
> perform this process.
> "Erland Sommarskog" wrote:
|||Sounds like you are blaming that hardware has not meet minimum requirement of
SQL 2005. However this system has PIII 600MHZ 896MB RAM (Windows 2003
recognize 896MB). It meets minimum requirement of 32bit SQL 2005.
Would you tell me what a expected time to finish this process on miminum
hardware requirement?
Thanks in advance
"Andrew J. Kelly" wrote:

> I don't know how you can get 896MB of memory, I suspect it is really 512MB.
> But in any case you are not meeting the minimum hardware requirements on CPU
> for SQL2005 let alone the recommended. As such I would expect it to be
> somewhat slow.
> http://www.microsoft.com/sql/editions/developer/sysreqs.mspx
> --
> Andrew J. Kelly SQL MVP
> "M. Matsuda" <MMatsuda@.discussions.microsoft.com> wrote in message
> news:A207A819-2286-4552-9EE4-3F4918687303@.microsoft.com...
>
>
|||M. Matsuda (MMatsuda@.discussions.microsoft.com) writes:
> SQL 2005 installed in Netfinity 5000 with 896MB RAM (P3 500M HZ) +
> Windows 2003 Server. SSMS and SQL 2005 reside on same machine. Before
> upgrade to SQL 2005, SQL 2000 run on same machine did not have any
> problem. Even SQL 2000 + Windows XP installed on notebook (Think pad
> 512MB RAM) + Visual Stuido 2005 run on same time does not have any
> problem to perform this process.
It is not very impressing hardware. And, yes, this problem with SQL Server
being very slow when it's low on memory is much more apparent with SQL 2005
than SQL 2000.
Did you use Task Manager to see how much memory SQL Server has when
performing the scripting operation?
If you have other processes running, for instance a web browser, try closing
these and see if it helps.
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/prodtechnol/sql/2005/downloads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodinfo/previousversions/books.mspx
|||Our tight budget won't allow me to upgrade fancy hardware as you may have and
still need to deal with limited resources and so do my small business clients
too.
I had a chance to test same process on IBM XS235 Xeon 3.06GHZ with 1.5GB RAM
relatively enough spec for SQL 2005 however it still took 7-8 minutes to get
response from SSMS. If this is ideal time to finish this process, I may need
to stick SQL 2000 for a while and recommend stay with SQL 2000 to my clients
for time being.
Thank you for your assistance.
"Erland Sommarskog" wrote:

> M. Matsuda (MMatsuda@.discussions.microsoft.com) writes:
> It is not very impressing hardware. And, yes, this problem with SQL Server
> being very slow when it's low on memory is much more apparent with SQL 2005
> than SQL 2000.
> Did you use Task Manager to see how much memory SQL Server has when
> performing the scripting operation?
> If you have other processes running, for instance a web browser, try closing
> these and see if it helps.
> --
> Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
> Books Online for SQL Server 2005 at
> http://www.microsoft.com/technet/prodtechnol/sql/2005/downloads/books.mspx
> Books Online for SQL Server 2000 at
> http://www.microsoft.com/sql/prodinfo/previousversions/books.mspx
>
|||M. Matsuda (MMatsuda@.discussions.microsoft.com) writes:
> Our tight budget won't allow me to upgrade fancy hardware as you may
> have and still need to deal with limited resources and so do my small
> business clients too.
Fancy and fancy. A 500 Mhz machine a certainly to reqard as an antiquity
today.

> I had a chance to test same process on IBM XS235 Xeon 3.06GHZ with 1.5GB
> RAM relatively enough spec for SQL 2005 however it still took 7-8
> minutes to get response from SSMS. If this is ideal time to finish this
> process, I may need to stick SQL 2000 for a while and recommend stay
> with SQL 2000 to my clients for time being.
I tried the exercise at home on a Pentium4 2.8 GHz with hyperthreading
and 1.5 GB of memory. I selected 275 procedures, and took about the time you
mentioned to script them. I noticed that SQL Server was eating a lot
of memory, around 440 MB, as well as CPU. For some reason that I don't
understand, Windows Explorer was also consuming CPU.
In this experiment, I selected the procedures from the Summary view.
The next thing I did was to use the scripting wizard. Right-click the
database node in Object Explorer and select Tasks->Generate Scripts.
It took about a minute for me to make the selection. (This database
has over 4000 thousand procedures, so I could not use Select all.)
But once started, the wizard completed within a minute. It may be
because SQL Server now had all it neded in memory. I need to play
with this a little more.
I agree with you that the performance is not satisfactory.
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/prodtechnol/sql/2005/downloads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodinfo/previousversions/books.mspx

Problem on insert using stored procedure

Here is my problem on SQL Server SP3a.
I have a table that reach more than 2 millions rows. My primary key is an
identity column.
From a Java program I'm calling a strored procedure to insert a new row in
that table and to get back the id of the new row using the scope_identity()
function.
I log the id returned by the first stored procedure and to ensure the line
has been added I call a second stored procedure to look if my line exists in
the table. That request returns a line and when I call a request from SQL
Server enterprise manager on my id I get no line in my table.
I really don't understand what can be my problem because it's not reccurent,
most of the time it's work fine. It seems that the first transaction is
sometimes rolled back by the systems.
If someone has an idea...
Stored procedure 1 to INSERT:
=============================
CREATE procedure SetIndFpsLogWeb
@.F_WobNum varchar(40)='' ,
@.codeuser varchar(30)='' ,
@.datedebutetat varchar(20)='',
@.datefinetat varchar(20)='',
@.datereception varchar(20)='',
@.datecreationdossier varchar(20)='',
@.numeroenregistrement varchar(16)='',
@.activites varchar(20)='' ,
@.produit varchar(4)='' ,
@.do varchar(4)='' ,
@.idclient varchar(12)='',
@.etatdossier varchar(2)='',
@.mediaentree varchar(4)='',
@.mediasortie varchar(4)='',
@.datefindossier varchar(20)='',
@.segmentclient varchar(12)='',
@.actions varchar(50)='' ,
@.etatexportdata varchar(1)='',
@.numeroenregistrementpli varchar(20)='' ,
@.taches varchar(50)='' ,
@.languecontactentrant varchar(4)='' ,
@.languecommunication varchar(4)='',
@.pays varchar(4)='' ,
@.datefinprevisionnelle varchar(20)='' ,
@.datelimitetraitement varchar(20)=''
AS
begin transaction
IF (@.numeroenregistrement <> '' AND @.numeroenregistrementpli ='' )
BEGIN
SET @.numeroenregistrementpli = @.numeroenregistrement
END
IF (@.actions<> '' )
BEGIN
if( SUBSTRING(@.actions, 1,1)=';')
BEGIN
SET @.actions = SUBSTRING(@.actions, 2, LEN(@.actions))
END
END
IF (@.taches<> '' )
BEGIN
if( SUBSTRING(@.taches, 1,1)=';')
BEGIN
SET @.taches = SUBSTRING(@.taches, 2, LEN(@.taches))
END
END
IF (@.activites<> '' )
BEGIN
if( SUBSTRING(@.activites, 1,1)=';')
BEGIN
SET @.activites= SUBSTRING(@.activites, 2, LEN(@.activites))
END
END
INSERT INTO ind_fps (
F_WobNum,
codeuser,
datedebutetat,
datefinetat,
datereception,
datecreationdossier,
numeroenregistrement,
activites,
produit,
do,
idclient,
etatdossier,
mediaentree,
mediasortie,
datefindossier,
segmentclient,
actions,
etatexportdata,
numeroenregistrementpli,
taches,
languecontactentrant,
languecommunication,
pays,
datefinprevisionnelle,
datelimitetraitement)
VALUES (
@.F_WobNum,
@.codeuser,
@.datedebutetat,
@.datefinetat,
@.datereception,
@.datecreationdossier,
@.numeroenregistrement,
@.activites,
@.produit,
@.do,
@.idclient,
@.etatdossier,
@.mediaentree,
@.mediasortie,
@.datefindossier,
@.segmentclient,
@.actions,
@.etatexportdata,
@.numeroenregistrementpli,
@.taches,
@.languecontactentrant,
@.languecommunication,
@.pays,
@.datefinprevisionnelle,
@.datelimitetraitement)
declare @.return varchar(500)
if @.@.error <> 0
begin
set @.return = 'ERROR : ' + cast(@.@.error as varchar)
rollback tran
end
else
begin
set @.return = scope_identity()
commit tran
end
select @.return
GO
Stored procedure 2 to GET:
==========================
CREATE procedure dbo.GetIndFpsInfosById
@.indfps_id varchar(20) = ''
as
begin transaction
SELECT *
FROM [ind_fps]
WHERE id = @.indfps_id
commit transaction
GO
Do not use a transaction in the second sp and use "set nocount on" in both
sps, as the first statement.
AMB
"edemasi" wrote:

> Here is my problem on SQL Server SP3a.
> I have a table that reach more than 2 millions rows. My primary key is an
> identity column.
> From a Java program I'm calling a strored procedure to insert a new row in
> that table and to get back the id of the new row using the scope_identity()
> function.
> I log the id returned by the first stored procedure and to ensure the line
> has been added I call a second stored procedure to look if my line exists in
> the table. That request returns a line and when I call a request from SQL
> Server enterprise manager on my id I get no line in my table.
> I really don't understand what can be my problem because it's not reccurent,
> most of the time it's work fine. It seems that the first transaction is
> sometimes rolled back by the systems.
> If someone has an idea...
> Stored procedure 1 to INSERT:
> =============================
> CREATE procedure SetIndFpsLogWeb
> @.F_WobNum varchar(40)='' ,
> @.codeuser varchar(30)='' ,
> @.datedebutetat varchar(20)='',
> @.datefinetat varchar(20)='',
> @.datereception varchar(20)='',
> @.datecreationdossier varchar(20)='',
> @.numeroenregistrement varchar(16)='',
> @.activites varchar(20)='' ,
> @.produit varchar(4)='' ,
> @.do varchar(4)='' ,
> @.idclient varchar(12)='',
> @.etatdossier varchar(2)='',
> @.mediaentree varchar(4)='',
> @.mediasortie varchar(4)='',
> @.datefindossier varchar(20)='',
> @.segmentclient varchar(12)='',
> @.actions varchar(50)='' ,
> @.etatexportdata varchar(1)='',
> @.numeroenregistrementpli varchar(20)='' ,
> @.taches varchar(50)='' ,
> @.languecontactentrant varchar(4)='' ,
> @.languecommunication varchar(4)='',
> @.pays varchar(4)='' ,
> @.datefinprevisionnelle varchar(20)='' ,
> @.datelimitetraitement varchar(20)=''
> AS
>
> begin transaction
> IF (@.numeroenregistrement <> '' AND @.numeroenregistrementpli ='' )
> BEGIN
> SET @.numeroenregistrementpli = @.numeroenregistrement
> END
> IF (@.actions<> '' )
> BEGIN
> if( SUBSTRING(@.actions, 1,1)=';')
> BEGIN
> SET @.actions = SUBSTRING(@.actions, 2, LEN(@.actions))
> END
> END
> IF (@.taches<> '' )
> BEGIN
> if( SUBSTRING(@.taches, 1,1)=';')
> BEGIN
> SET @.taches = SUBSTRING(@.taches, 2, LEN(@.taches))
> END
> END
> IF (@.activites<> '' )
> BEGIN
> if( SUBSTRING(@.activites, 1,1)=';')
> BEGIN
> SET @.activites= SUBSTRING(@.activites, 2, LEN(@.activites))
> END
> END
> INSERT INTO ind_fps (
> F_WobNum,
> codeuser,
> datedebutetat,
> datefinetat,
> datereception,
> datecreationdossier,
> numeroenregistrement,
> activites,
> produit,
> do,
> idclient,
> etatdossier,
> mediaentree,
> mediasortie,
> datefindossier,
> segmentclient,
> actions,
> etatexportdata,
> numeroenregistrementpli,
> taches,
> languecontactentrant,
> languecommunication,
> pays,
> datefinprevisionnelle,
> datelimitetraitement)
> VALUES (
> @.F_WobNum,
> @.codeuser,
> @.datedebutetat,
> @.datefinetat,
> @.datereception,
> @.datecreationdossier,
> @.numeroenregistrement,
> @.activites,
> @.produit,
> @.do,
> @.idclient,
> @.etatdossier,
> @.mediaentree,
> @.mediasortie,
> @.datefindossier,
> @.segmentclient,
> @.actions,
> @.etatexportdata,
> @.numeroenregistrementpli,
> @.taches,
> @.languecontactentrant,
> @.languecommunication,
> @.pays,
> @.datefinprevisionnelle,
> @.datelimitetraitement)
> declare @.return varchar(500)
> if @.@.error <> 0
> begin
> set @.return = 'ERROR : ' + cast(@.@.error as varchar)
> rollback tran
> end
> else
> begin
> set @.return = scope_identity()
> commit tran
> end
> select @.return
> GO
> Stored procedure 2 to GET:
> ==========================
> CREATE procedure dbo.GetIndFpsInfosById
> @.indfps_id varchar(20) = ''
> as
> begin transaction
> SELECT *
> FROM [ind_fps]
> WHERE id = @.indfps_id
> commit transaction
> GO
>