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

Friday, March 23, 2012

Problem Reading Image Data from SQL Server using ADO.NET

Hi Community,
I think I can store Binary Data in SQL Server but when I try to retrieve it,
I always only get one byte.
I think I stored my Binary Data in SQL Server in a Colum of Type Image. At
least when I execute the following code, I get some significant network
traffic. When I check the database with query analyzer, I see 4 Hex Chars in
the image colum. Like 0xe0 etc.
This is my first Question, does this mean that only 4 Bytes ended up in the
Database and my problem starts here or is this the preview mode of the image
daty type in query analyzer like I suppose?
Store Image to SQL-Server:
float[] image = MyImageData in a One Dimensional Float Array;
int byte_size = image.length * 4;
byte[] image_buffer = new byte[byte_size];
Buffer. BlockCopy(image,0,image_buffer,0,byte_si
ze);
cmd = new SqlCommand("AddImage",Conn);
cmd.CommandType = CommandType.StoredProcedure;
param = new SqlParameter("@.blob", SqlDbType.VarBinary, image_buffer.Length,
ParameterDirection.Input, false, 0, 0, null,
DataRowVersion.Current,image_buffer);
cmd.Parameters.Add(param);
Conn.Open();
cmd.ExecuteNonQuery();
Conn.Close();
As I already said, regarding the network traffic and the amount of time it
takes to execute this code, I think my image data is in sql server now.
When I try to retrieve it, I always only get one byte per Image.
Retreive Image-Data:
Conn.Open();
int chunkSize = 255;
using(reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess))
{
while (reader.Read())
{
long bytesize = reader.GetBytes(5, 0, null, 0, 0);
byte[] imageData = new byte[bytesize]; //This always returns 1
long bytesread = 0;
int curpos = 0;
while (bytesread < bytesize)
{
bytesread += reader.GetBytes(5, curpos, imageData, curpos, chunkSize);
curpos += chunkSize;
}
Buffer.BlockCopy(imageData,0,result.data,curpos*byteoffset,byteoffset);
}
}
The Code above is from ado documentation. It says that after this loop, the
bytes from the imagedata colum are in the imagedata array. In my case I
always only get one byte.
I don′t have significant network traffic reading from sql-server there is
realy only one byte transfered.
Can somebody please tell me, what I am doing wrong and how I can check if
the data i want to retreive is realy in the database.
Can you see the full content of a image field in query analyzer?
What happened to the rest of my data, I don′t get an index out of bound
exception when I fill in 65000 Bytes but there seems to be only one byte
there afterwards.
Thanks in advance for your efforts
Best Regards
Chucker"Chucker" <Chucker@.discussions.microsoft.com> wrote in message
news:CC4F035E-EF80-4775-94CE-8F45FDC2DF2F@.microsoft.com...
> Hi Community,
> I think I can store Binary Data in SQL Server but when I try to retrieve
> it,
> I always only get one byte.
> I think I stored my Binary Data in SQL Server in a Colum of Type Image. At
> least when I execute the following code, I get some significant network
> traffic. When I check the database with query analyzer, I see 4 Hex Chars
> in
> the image colum. Like 0xe0 etc.
> This is my first Question, does this mean that only 4 Bytes ended up in
> the
> Database and my problem starts here or is this the preview mode of the
> image
> daty type in query analyzer like I suppose?
>
I can't see anything particularly wrong with the code you posted.
Here's a complete working example (.net 2.0);
using System;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Diagnostics;
public class Program
{
static void Main(string[] args)
{
System.Diagnostics.Debug.Listeners.Add(new
TextWriterTraceListener(Console.Out));
try
{
SqlConnectionStringBuilder cb = new SqlConnectionStringBuilder();
cb.IntegratedSecurity = true;
cb.DataSource = "(local)";
using (SqlConnection con = new SqlConnection(cb.ConnectionString))
{
con.Open();
new SqlCommand("create table #blobtest(id int identity primary key,
blob image)",con).ExecuteNonQuery();
float[] image = new float[5000];
image[image.Length -1] = 4f;
int byte_size = image.Length * sizeof(float);
byte[] image_buffer = new byte[byte_size];
Buffer. BlockCopy(image,0,image_buffer,0,byte_si
ze);
SqlCommand cmdInsert = new SqlCommand("insert into #blobtest(blob)
values (@.blob)", con);
SqlParameter param = cmdInsert.Parameters.Add(new
SqlParameter("@.blob",
SqlDbType.Image,
image_buffer.Length));
param.Value = image_buffer;
cmdInsert.ExecuteNonQuery();
//now read
int chunkSize = 255;
SqlCommand cmdRead = new SqlCommand("select id, datalength(blob)
bytes, blob from #blobtest", con);
using (SqlDataReader reader =
cmdRead.ExecuteReader(CommandBehavior.SequentialAccess))
{
while (reader.Read())
{
int actualBytes = reader.GetInt32(1);
long bytesize = reader.GetBytes(2, 0, null, 0, 0);
Console.WriteLine("Actual Bytes: {0}, GetBytes reported {1}",
actualBytes, bytesize);
byte[] buf = new byte[chunkSize * sizeof(float)];
float[] nums = new float[bytesize/sizeof(float)];
int bytesread = 0;
while (bytesread < bytesize)
{
int bytes = (int)reader.GetBytes(2, bytesread, buf, 0,
buf.Length);
Buffer.BlockCopy(buf, 0, nums, bytesread, bytes);
bytesread += bytes;
}
Console.WriteLine("nums length {0}, first {1}, last {2}",
nums.Length, nums[0], nums[nums.Length - 1]);
}
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
Console.WriteLine("Hit any key to exit.");
Console.ReadKey();
}
}
David|||Thanks David, you are right, i made a very stupid mistake, I wrote binary
instead of varbinary in one place thanks for your help
Chucker
"David Browne" wrote:

> "Chucker" <Chucker@.discussions.microsoft.com> wrote in message
> news:CC4F035E-EF80-4775-94CE-8F45FDC2DF2F@.microsoft.com...
> I can't see anything particularly wrong with the code you posted.
> Here's a complete working example (.net 2.0);
> using System;
> using System.Data;
> using System.Data.SqlClient;
> using System.Collections.Generic;
> using System.Diagnostics;
> public class Program
> {
> static void Main(string[] args)
> {
> System.Diagnostics.Debug.Listeners.Add(new
> TextWriterTraceListener(Console.Out));
> try
> {
> SqlConnectionStringBuilder cb = new SqlConnectionStringBuilder();
> cb.IntegratedSecurity = true;
> cb.DataSource = "(local)";
> using (SqlConnection con = new SqlConnection(cb.ConnectionString))
> {
> con.Open();
> new SqlCommand("create table #blobtest(id int identity primary key
,
> blob image)",con).ExecuteNonQuery();
>
> float[] image = new float[5000];
> image[image.Length -1] = 4f;
> int byte_size = image.Length * sizeof(float);
> byte[] image_buffer = new byte[byte_size];
> Buffer. BlockCopy(image,0,image_buffer,0,byte_si
ze);
> SqlCommand cmdInsert = new SqlCommand("insert into #blobtest(blob)
> values (@.blob)", con);
> SqlParameter param = cmdInsert.Parameters.Add(new
> SqlParameter("@.blob",
> SqlDbType.Image,
> image_buffer.Length));
> param.Value = image_buffer;
> cmdInsert.ExecuteNonQuery();
>
> //now read
> int chunkSize = 255;
> SqlCommand cmdRead = new SqlCommand("select id, datalength(blob)
> bytes, blob from #blobtest", con);
> using (SqlDataReader reader =
> cmdRead.ExecuteReader(CommandBehavior.SequentialAccess))
> {
> while (reader.Read())
> {
> int actualBytes = reader.GetInt32(1);
> long bytesize = reader.GetBytes(2, 0, null, 0, 0);
> Console.WriteLine("Actual Bytes: {0}, GetBytes reported {1}",
> actualBytes, bytesize);
> byte[] buf = new byte[chunkSize * sizeof(float)];
> float[] nums = new float[bytesize/sizeof(float)];
> int bytesread = 0;
> while (bytesread < bytesize)
> {
> int bytes = (int)reader.GetBytes(2, bytesread, buf, 0,
> buf.Length);
> Buffer.BlockCopy(buf, 0, nums, bytesread, bytes);
> bytesread += bytes;
> }
> Console.WriteLine("nums length {0}, first {1}, last {2}",
> nums.Length, nums[0], nums[nums.Length - 1]);
> }
> }
> }
> }
> catch (Exception ex)
> {
> Console.WriteLine(ex);
> }
> Console.WriteLine("Hit any key to exit.");
> Console.ReadKey();
> }
> }
>
>
>
>
> David
>
>

Problem querying linked server

I have a problem querying a linked server (Oracle) from my SQL server 2000. I am able to query it normally but when I try to do it through a stored procedure i get the following message

Msg 7399, Sev 16: OLE DB provider 'MSDAORA' reported an error. Authentication failed. [SQLSTATE 42000]
Msg 7312, Sev 16: [SQLSTATE 01000]
Msg 7300, Sev 16: OLE DB error trace [OLE/DB Provider 'MSDAORA' IDBInitialize::Initialize returned 0x80040e4d: Authentication failed.]. [SQLSTATE 01000]Can anybody help me ??

Originally posted by Enigma
I have a problem querying a linked server (Oracle) from my SQL server 2000. I am able to query it normally but when I try to do it through a stored procedure i get the following message

Msg 7399, Sev 16: OLE DB provider 'MSDAORA' reported an error. Authentication failed. [SQLSTATE 42000]
Msg 7312, Sev 16: [SQLSTATE 01000]
Msg 7300, Sev 16: OLE DB error trace [OLE/DB Provider 'MSDAORA' IDBInitialize::Initialize returned 0x80040e4d: Authentication failed.]. [SQLSTATE 01000]|||Looks like you may have a problem with your access rights on either one of the servers......|||Well,

I am able to query the server when I am in the sql query analyzer.
I.E.
SELECT * INTO ABCD FROM TESTSVR..USER.ABCD

This works perfectly and i get the result

When I try to run this as a stored procedure

CREATE procedure sp_TransferData @.server varchar(100),@.userid varchar(30)
as
declare
@.tablename varchar (30),
@.fieldnametemp varchar(100),
@.query varchar (2500)
declare tablenames cursor for
select distinct table_name from TABLES

open tablenames
FETCH NEXT FROM tablenames into @.tablename
WHILE @.@.FETCH_STATUS = 0
begin
declare @.fieldname varchar(2000)
select @.fieldname = ''
declare fieldname cursor for
select field_name from tables where table_name = @.tablename
open fieldname
FETCH NEXT FROM fieldname into @.fieldnametemp
WHILE @.@.FETCH_STATUS = 0
begin
select @.fieldname = @.fieldnametemp + ',' + @.fieldname
fetch next from fieldname into @.fieldnametemp
end
CLOSE fieldname
DEALLOCATE fieldname
select @.fieldname = left(@.fieldname,len(@.fieldname)-1)
select @.query = 'select '+ @.fieldname + ' into ' + @.tablename + ' from ' + @.server + '..' + @.userid + '.' + @.tablename + ''')'
select @.query

execute (@.query)
print 'Table Processed'

fetch next from tablenames into @.tablename
end

CLOSE tablenames
DEALLOCATE tablenames

the error crops up ... can somebody suggest a way around

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 parameter into remote stored proc

I'm having a problem passing a parameter value into a stored procedure
that I am running on a remote (linked) server, and am receiving a DTC
error because of it.
I have a stored procedure that brings in a variable (@.CustID int). I
later pass that parameter to another stored procedure. The code looks
like this...
EXEC LinkedServer.dbname.dbo.spname @.CustID
When I run that, I get this error...
Server: Msg 7391, Level 16, State 1, Procedure spname, Line 394
The operation could not be performed because the OLE DB provider
'SQLOLEDB' was unable to begin a distributed transaction.
OLE DB error trace [OLE/DB Provider 'SQLOLEDB'
ITransactionJoin::JoinTransaction returned 0x8004d00a].
[OLE/DB provider returned message: New transaction cannot enlist in the
specified transaction coordinator. ]
However, if I hard-code the parameter, it works:
EXEC LinkedServer.dbname.dbo.spname 1234 -- this works.
I can even do this:
DECLARE @.var int
SET @.var = 1234
EXEC LinkedServer.dbname.dbo.spname @.var -- this works too.
But if I accept the variable as an input parameter to my stored
procedure, I get the error listed above.
Any ideas?
Thanks in advance for your help...
Zev Steinhardtzev_steinhardt
what happen if you assign the parameter to a variable?
DECLARE @.var int
SET @.var = @.CustID
EXEC LinkedServer.dbname.dbo.spname @.var
...
AMB
"zev_steinhardt" wrote:

> I'm having a problem passing a parameter value into a stored procedure
> that I am running on a remote (linked) server, and am receiving a DTC
> error because of it.
> I have a stored procedure that brings in a variable (@.CustID int). I
> later pass that parameter to another stored procedure. The code looks
> like this...
> EXEC LinkedServer.dbname.dbo.spname @.CustID
> When I run that, I get this error...
> Server: Msg 7391, Level 16, State 1, Procedure spname, Line 394
> The operation could not be performed because the OLE DB provider
> 'SQLOLEDB' was unable to begin a distributed transaction.
> OLE DB error trace [OLE/DB Provider 'SQLOLEDB'
> ITransactionJoin::JoinTransaction returned 0x8004d00a].
> [OLE/DB provider returned message: New transaction cannot enlist in the
> specified transaction coordinator. ]
> However, if I hard-code the parameter, it works:
> EXEC LinkedServer.dbname.dbo.spname 1234 -- this works.
> I can even do this:
> DECLARE @.var int
> SET @.var = 1234
> EXEC LinkedServer.dbname.dbo.spname @.var -- this works too.
> But if I accept the variable as an input parameter to my stored
> procedure, I get the error listed above.
> Any ideas?
> Thanks in advance for your help...
> Zev Steinhardt
>|||Thanks for the reply, Alejandro.
I tried that. It didn't work.
I even tried to trick it into thinking that it's another variable
altogether. I put the variable into a temp table, declared a new
variable, populated it with the value from the temp table and passed it
in. That didn't work either.
Zev Steinhardt|||zev_steinhardt,
Are you executing the remote sp inside a transaction?
AMB
"zev_steinhardt" wrote:

> Thanks for the reply, Alejandro.
> I tried that. It didn't work.
> I even tried to trick it into thinking that it's another variable
> altogether. I put the variable into a temp table, declared a new
> variable, populated it with the value from the temp table and passed it
> in. That didn't work either.
> Zev Steinhardt
>|||Yes. The remote sp is within a transaction.
Zev|||zev_steinhardt,
you are using a distributed one, correct?
begin distributed transaction
exec ...
AMB
"zev_steinhardt" wrote:

> Yes. The remote sp is within a transaction.
> Zev
>|||Alejandro...
Yes, it is a distributed transaction... and I have XACT_ABORT on
Zev|||zev_steinhardt,
When you execute the remote sp using:
DECLARE @.var int
SET @.var = 1234
EXEC LinkedServer.dbname.dbo.spname @.var -- this works too.
then you are not executing it using a distributed transaction, that is why
you do not get the error.
See if this helps.
You receive error 7391 when you run a distributed transaction against a
linked server
http://support.microsoft.com/kb/329332/en-us
AMB
"zev_steinhardt" wrote:

> Alejandro...
> Yes, it is a distributed transaction... and I have XACT_ABORT on
> Zev
>

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.