Tracking Forums, Newsgroups, Maling Lists
Home Scripts Tutorials Tracker Forums
  Advanced Search
  HOME    TRACKER    MS SQL Server


SuperbHosting.net have generously sponsored dedicated servers to ensure a reliable and scalable dedicated hosting solution for BigResource.com.





Can A Stored Procedure Called From An Inline Table-Valued Function


Hi,

I'm trying to call a Stored Procedure from a Inline Table-Valued Function. Is it possible? If so can someone please tell me how? And also I would like to call this function from a view. Can it be possible? Any help is highly appreciated. Thanks




View Complete Forum Thread with Replies

Related Forum Messages:
Inline Table-valued Function With Multi-value Parameter
Hello everybody,

I need to create a function which takes a multi-value parameter. When I select more than one item, I get the error that I have too many arguments. Does anybody have a solution?

Or can I create a view and then do a "SELECT * FROM viewName WHERE columnName IN (@param)"?

Thanks in advance for your answers.

View Replies !
How Can I Assign Data Returned From A Stored Procedure Into The Return Table Of A Table Valued Function
Here is the scenario,
I have 2 stored procedures, SP1 and SP2

SP1 has the following code:

declare @tmp as varchar(300)
set @tmp = 'SELECT * FROM
OPENROWSET ( ''SQLOLEDB'', ''SERVER=.;Trusted_Connection=yes'',
''SET FMTONLY OFF EXEC ' + db_name() + '..StoredProcedure'' )'

EXEC (@tmp)

SP2 has the following code:

SELECT *
FROM SP1 (which won't work because SP1 is a stored procedure. A view, a table valued function, or a temporary table must be used for this)

Views - can't use a view because they don't allow dynamic sql and the db_name() in the OPENROWSET function must be used.
Temp Tables - can't use these because it would cause a large hit on system performance due to the frequency SP2 and others like it will be used.
Functions - My last resort is to use a table valued function as shown:

FUNCTION MyFunction
( )
RETURNS @retTable
(
@Field1 int,
@Field2 varchar(50)
)
AS
BEGIN
-- the problem here is that I need to call SP1 and assign it's resulting data into the
-- @retTable variable

-- this statement is incorrect, but it's meaning is my goal
INSERT @retTableSELECT *FROM SP1

RETURN
END

View Replies !
Calling CLR Stored Procedure From Within A CLR Table-valued Function Giving Errors
We are trying to create a TVF that executes a CLR Stored Procedure we wrote to use the results from the SP and transform them for the purposes of returning to the user as a table.

 




Code Snippet

[SqlFunction ( FillRowMethodName = "FillRow",

TableDefinition = "CustomerID nvarchar(MAX)",

SystemDataAccess = SystemDataAccessKind.Read,

DataAccess = DataAccessKind.Read,

IsDeterministic=false)]

public static IEnumerable GetWishlist () {

using (SqlConnection conn = new SqlConnection ( "Context Connection=true" )) {

List<string> myList = new List<string> ();

conn.Open ();

SqlCommand command = conn.CreateCommand ();

command.CommandText = "GetObject";

command.Parameters.AddWithValue ( "@map", "Item" );

command.CommandType = System.Data.CommandType.StoredProcedure;

using ( SqlDataReader reader = command.ExecuteReader ( System.Data.CommandBehavior.SingleRow )) {

if (reader.Read ()) {

myList.Add ( reader[0] as string );

}

}



return (IEnumerable)myList;

}

}

 

When command.ExecuteReader is called, I am getting an "Object not defined" error.  However, the stored procedure can be used in SQL Management Studio just fine.

 




Code SnippetEXEC GetObject 'Item'

 

Is there some sorf of trick I am missing?

 

Thank you!

 

View Replies !
Retrieving Result Set From Dynamically Called Stored Procedure Or Function In A Function
Is there any way I can retrieve the result set of a Stored Procedurein a function.ALTER FUNCTION dbo.fn_GroupDeviceLink(@groupID numeric)RETURNS @groupDeviceLink TABLE (GroupID numeric, DeviceID numeric)ASBEGINDeclare @command nvarchar(255)SELECT @command = Condition// @command is an SQL string or stored procedue nameFROM DeviceGroupWHERE GroupID = @groupIDINSERT @groupDeviceLinkEXEC @commandRETURNENDIs there any way i can do anything like this. @command is a variableholding the name of a stored produre. I need to run that storedprocure and return the values in such a way that they can be used in aSELECT StatementMy goal is SELECT * FROM Device INNER JOINdbo.fn_GroupDeviceLink(@groupID) ON ....this fn_GroupDeviceLink should run the proper stored procedure andreturn the values. What i also want to do is play with that result setof the specific stored procedure before i return it. Is this possible?If not, what is the work arround?ThanksMark

View Replies !
Inline-table-valued Functions
Help! Been doing the box step with BOL for several hours , Using tables in Adventureworks to create inline-table-valued function to provide a parameterized view of three JOINS - Have sucessfully created the function but can't figure out where to 'Declare' my variable "@SalesAgentID" need to be able to invoke the function with a particular ID - If you can help me cut this dance short I would REALLY Appreciate it.

View Replies !
Using A Scalar Valued Function As A Parameter Of A Table Valued Function?
Ok, I'm pretty knowledgable about T-SQL, but I've hit something that seems should work, but just doesn't...
I'm writing a stored procedure that needs to use the primary key fields of a table that is being passed to me so that I can generate what will most likely be a dynamically generated SQL statement and then execute it.
So the first thing I do, is I need to grab the primary key fields of the table.  I'd rather not go down to the base system tables since we may (hopefully) upgrade this one SQL 2000 machine to 2005 fairly soon, so I poke around, and find sp_pkeys in the master table.  Great.  I pass in the table name, and sure enough, it comes back with a record set, 1 row per column.  That's exactly what I need.
Umm... This is the part where I'm at a loss.  The stored procedure outputs the resultset as a resultset (Not as an output param).  Now I want to use that list in my stored procedure, thinking that if the base tables change, Microsoft will change the stored procedure accordingly, so even after a version upgrade my stuff SHOULD still work.  But... How do I use the resultset from the stored procedure?  You can't reference it like a table-valued function, nor can you 'capture' the resultset for use using the  syntax like:
DECLARE @table table@table=EXEC sp_pkeys MyTable
That of course just returns you the RETURN_VALUE instead of the resultset it output.  Ugh.  Ok, so I finally decide to just bite the bullet, and I grab the code from sp_pkeys and make my own little function called fn_pkeys.  Since I might also want to be able to 'force' the primary keys (Maybe the table doesn't really have one, but logically it does), I decide it'll pass back a comma-delimited varchar of columns that make up the primary key.  Ok, I test it and it works great.
Now, I'm happily going along and building my routine, and realize, hey, I don't really want that in a comma-delimited varchar, I want to use it in one of my queries, and I have this nice little table-valued function I call split, that takes a comma-delimited varchar, and returns a table... So I preceed to try it out...
SELECT *FROM Split(fn_pkeys('MyTable'),DEFAULT)
Syntax Error.  Ugh.  Eventually, I even try:
SELECT *FROM Split(substring('abc,def',2,6),DEFAULT)
Syntax Error.
Hmm...What am I doing wrong here, or can't you use a scalar-valued function as a parameter into a table-valued function?
SELECT *FROM Split('bc,def',DEFAULT) works just fine.
So my questions are:
Is there any way to programmatically capture a resultset that is being output from a stored procedure for use in the stored procedure that called it?
Is there any way to pass a scalar-valued function as a parameter into a table-valued function?
Oh, this works as well as a work around, but I'm more interested in if there is a way without having to workaround:
DECLARE @tmp varchar(8000)
SET @tmp=(SELECT dbo.fn_pkeys('MyTable'))
SELECT *
FROM Split(@tmp,DEFAULT)

View Replies !
Problem With Stored Procedure And Table-valued Functions
Hello Gurus,
I have a stored procedure that gathers data from three tables and joins them, two of the tables need to have different rowcounts set, ie. pull only a certain number of rows from one table and only a certain number of rows from another table...  The number of rows it should pull are stored within a table for each.  Let me explain.... these tables hold Exchange storage group and mailstore data for a number of servers.  Each server has a table entry with the number of child storage groups and each storage group has a table entry with the number of child mailstores.  The tables get updated every two minutes via a program.  I need to be able to get the most Data with the correct child counts for each server and storage group. 
I believe that i've found a way to do this with a stored procedure that calls a table-valued function.  The table-valued function simply filters down the storage group table to it's number of storage groups, ordered by timestamp. I may be way off here, but i can't tell because both the stored procedure and function check out fine but when i execute the stored procedure it gives me the following error:
 Cannot find either column "dbo" or the user-defined function or aggregate "dbo.GetExchSGInfo", or the name is ambiguous.
 
My code is below:
Stored Procedure:
 SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[GetExchangeData2]

@top INT,
@SID INT,
@SGCount INT,
@ServerName VARCHAR(50)

AS

Set @SID = (SELECT ServerID FROM dbo.Servers WHERE ServerName = @ServerName)
Set @top = (SELECT sum(Children) FROM dbo.ExchangeSG WHERE ServerID = @SID)
Set @SGCount = (SELECT SGCount FROM dbo.Servers WHERE ServerID = @SID)

SET ROWCOUNT @top
SELECT dbo.ExchangeMSData.*, dboExchangeMailStore.*, dbo.GetExchSGInfo(@SID,@SGCount) As ExchangeSG, dbo.Servers.*
FROM dbo.Servers INNER JOIN
ExchangeSG ON dbo.Servers.ServerID = ExchangeSG.ServerID INNER JOIN
dbo.ExchangeMailStore ON ExchangeSG.StorageGroupID = dbo.ExchangeMailStore.StorageGroupID INNER JOIN
dbo.ExchangeMSData ON dbo.ExchangeMailStore.MailstoreID = dbo.ExchangeMSData.MailstoreID
WHERE (dbo.Servers.ServerName = @ServerName)
ORDER BY dbo.ExchangeMSData.[TimeStamp] DESC, dbo.ExchangeSG.[TimeStamp] DESC

SET ROWCOUNT 0






 And the Function:
 SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE FUNCTION [dbo].[GetExchSGInfo]
(
@SID INT,
@SGCount INT
)
RETURNS TABLE
AS
RETURN
(
SELECT TOP (@SGCount) *
FROM dbo.ExchangeSG
WHERE ServerID = @SID
ORDER BY [TimeStamp]
)
 
 
Can anyone help me?
Thanks.

View Replies !
In-Line Table-Valued Function: How To Get The Result Out From The Function?
Hi all,
 
I executed the following sql script successfuuly:
 
shcInLineTableFN.sql:

USE pubs

GO

CREATE FUNCTION dbo.AuthorsForState(@cState char(2))

RETURNS TABLE

AS

RETURN (SELECT * FROM Authors WHERE state = @cState)

GO
 
And the "dbo.AuthorsForState" is in the Table-valued Functions, Programmabilty, pubs Database.
 
I tried to get the result out of the "dbo.AuthorsForState" by executing the following sql script:
 
shcInlineTableFNresult.sql:

USE pubs

GO

SELECT * FROM shcInLineTableFN

GO

 
I got the following error message:

Msg 208, Level 16, State 1, Line 1

Invalid object name 'shcInLineTableFN'.

 
Please help and advise me how to fix the syntax

"SELECT * FROM shcInLineTableFN"
and get the right table shown in the output.
 
Thanks in advance,
Scott Chang

View Replies !
Table-Valued Function
I am new to writing table-valued user defined function, so this might be a 'Duh' question. I am trying to write a table-valued UDF that has to return multiple rows. How do I do this?
 
Thanks

Mangala

View Replies !
Using OPTION Clause Within CREATE FUNCTION Statement For Inline Table Functions
Hi!
 
I need to expand resursion level for resursive CTE expression within CREATE FUNCTION statement for inline table function to a value greater than default. It turns out that OPTION clause for MAXRECURSION hint perfectly works if I use it outside CREATE FUNCTION (as well as CREATE VIEW for non-parametrized queries), but  it does not within CREATE FUNCTION statement - I'm getting error:

Msg 156, Level 15, State 1, Procedure ExpandedCTE, Line 34

Incorrect syntax near the keyword 'option'.
 
Here is the function:
 

create FUNCTION [dbo].[ExpandedCTE]

(

@p_id int

)

RETURNS TABLE

AS

RETURN

(

with tbl_cte (id, tbl_id, lvl)

as

(

select


id, tbl_id, 0 lvl

from


tbl

where


id = @p_id

union all

select


t.id, t.tbl_id, lvl + 1
from

tbl_cte
inner join tbl t


on rnr.tbl_id = tbl_cte.id

)

select


id, tbl_id, lvl

from


tbl_cte

option (maxrecursion 0)

)

 
Please help!  
 
Alexander.

 
P.S.
I'm really sorry if it is about syntax, but I could not find it in the documentation.

View Replies !
Trigger On Table-valued Function?
Is there a way to create a trigger directly on an inline or multi-line tablevalue function?I am trying to create a quick-and-dirty application using an Access DataProject front-end with SQL 2000 SP3 EE.Thanks.

View Replies !
Table Valued Function And Constraints
 

Is it possible to define a constraint for Primary Key on more than 1 column or an alternate index on a column in a return table from an inline table valed function?
 
Example Header:
 

alter FUNCTION [dbo].[fntMetaFrame] (@ii_CompanyID int)

RETURNS @tbl_MetaFrame TABLE ( pk_Key int Identity(1,1) primary key,






ObjectID int ,







Seq int null )



 
I want the primary key to be pk_Key, ObjectID
 
OR
 
I want to add another index on ObjectID.

View Replies !
How To Join Using A Table-valued Function?
Hi there.    I've hit some gap in my SQL fundementals.   I'm playing with table-valued functions but I can't figure out how to join those results with another table.   I found another way to hit my immediate need with a scalar function, but ultimately I'm going to need to use some approach like this.   What am I misunderstanding here?

The Given Objects:
function Split(stringToSplit, delimiter)   returns table (column:  token)
table Words  (column: Words.word)     -- table of predefined words
table Sentences  (column:  Sentences.sentence)    --  table of sentences; tokens may not be in Words table, etc

The Problems:
1) how do I query a set of Sentences and their Tokens?   (using Split)
2) how do I join tables Sentences and Words using the Split function?

The Attempts:
A)
select word, sentence, token
from Words,
       Sentences,
       dbo.Split(sentence, ' ')      -- implicitly joins Split result with Sentences?
where  word = token

resulting error:   "'sentence' is not a recognized OPTIMIZER LOCK HINTS option."

B)
select word, sentence
from Words, Sentences
where word in (select token from dbo.Split(sentence, ' '))   -- correlated subquery?

resulting error:   "'sentence' is not a recognized OPTIMIZER LOCK HINTS option."

View Replies !
Indexing Table-valued Function?
I am using a multi-statement table-valued function to assemble data from several tables and views for a report.  To do this, I INSERT data into the first few columns and then use UPDATEs to put data additional data into each row.  Each UPDATE uses a WHERE criteria that identifies a unique row, based on the value of the first few columns. 
 
The problem I'm having is that the UPDATEs are taking forever to execute.  I believe the reason is that the temporary table that's created for the function is not indexed, so each row update requires a complete search of several columns.
 
In other situations I've been able to define one column as a primary key for the temporary table, but in this situation the primary key would have to consist of four columns, which doesn't seem to be allowed in the table definition for the function.
 
Is there any way to create indexes for the temporary tables that are created for multistatement table-valued functions?  I think that would improve the UPDATE performance dramatically.
 
Thanks,
Lee Silverman
JackRabbit Sports

View Replies !
Can I Use If Statement In A Table Valued Function?
hi,
I am using a function in sql server 2005 like this:
...... myfunction(... @FlagOn int)
.......
begin
return
(

if(@FlagOn = 1)
select * from.......
else
select * form....
)
end
 
But it keeps complaining there is some syntax error around if. What is it?
 
Thanks.
 

View Replies !
Join With Table Valued Function
Hi,

I want to join a table valued function but function parameter should left joined table's primary key .... this is posible in oracle by pipeline method ..
eg..
SELECT A.Col1,A.Col2,B.Col1,B.Col2
FROM Tab As A LEFT OUTER JOIN TblFunction(A.Pkey) B
ON A.Col1 = B.Col1

any body help me ... thanx in advance..

View Replies !
Converting An Inline Sql To A Stored Procedure
Hi i have the following method in my page, it works fine and everything, but i am trying to modify it so that it can take a stored procedure;
 protected void Button1_Click(object sender, EventArgs e)
{SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["streamConnectionString"].ConnectionString);String sql = "SELECT userID, userName FROM users WHERE userName LIKE " + "'" + userName.Text + "%' OR organisation= " + "'" + OrganisationList.SelectedValue + "'";
conn.Open();
SqlCommand comm = new SqlCommand(sql, conn);SqlDataReader reader = comm.ExecuteReader(CommandBehavior.CloseConnection);
DataList1.DataSource = reader;
DataList1.DataBind();
conn.Close();
}
 
My question is what should my stored procedure be, and also how will i now structure the above method.

View Replies !
Changing A Stored Procedure To Inline Sql
Hi i have the following stored procedure, i am trying to convert it to inline sql, however i got stuck,  because how would i output a value e.g "@Access_Right_ID",  this is the stored procedure below
CREATE PROCEDURE dhoc_AccessRight_Insert  @AccessLevel char(50), @Access_Right_ID int OUT,
 @Tstamp timestamp out
 ASSELECT * FROM tblAccess_Right
WHERE AccessLevel = @AccessLevel IF @@ROWCOUNT <>0   BEGIN         RAISERROR('This record is already in the database',16,1)         RETURN 14    END
ELSE   BEGIN SET NOCOUNT OFF;             INSERT INTO tblAccess_Right (   AccessLevel ) VALUES (@AccessLevel);            SET @Access_Right_ID = @@Identity            SET @Tstamp = (SELECT Tstamp FROM tblAccess_Right WHERE Access_Right_ID=@Access_Right_ID)
      --Make sure this has saved, if not return 10 as this is unexpected error     IF @@rowcount = 0 BEGIN                    RAISERROR('This record has not been inserted at this time, it might have been inserted by another user, please try again',16,1)        RETURN 10 END     ELSE          BEGIN  IF @@error <>0 BEGIN    RETURN @@error            END     ENDEND
GO

View Replies !
Grab IDENTITY From Called Stored Procedure For Use In Second Stored Procedure In ASP.NET Page
I have a sub that passes values from my form to my stored procedure.  The stored procedure passes back an @@IDENTITY but I'm not sure how to grab that in my asp page and then pass that to my next called procedure from my aspx page.  Here's where I'm stuck:    Public Sub InsertOrder()        Conn.Open()        cmd = New SqlCommand("Add_NewOrder", Conn)        cmd.CommandType = CommandType.StoredProcedure        ' pass customer info to stored proc        cmd.Parameters.Add("@FirstName", txtFName.Text)        cmd.Parameters.Add("@LastName", txtLName.Text)        cmd.Parameters.Add("@AddressLine1", txtStreet.Text)        cmd.Parameters.Add("@CityID", dropdown_city.SelectedValue)        cmd.Parameters.Add("@Zip", intZip.Text)        cmd.Parameters.Add("@EmailPrefix", txtEmailPre.Text)        cmd.Parameters.Add("@EmailSuffix", txtEmailSuf.Text)        cmd.Parameters.Add("@PhoneAreaCode", txtPhoneArea.Text)        cmd.Parameters.Add("@PhonePrefix", txtPhonePre.Text)        cmd.Parameters.Add("@PhoneSuffix", txtPhoneSuf.Text)        ' pass order info to stored proc        cmd.Parameters.Add("@NumberOfPeopleID", dropdown_people.SelectedValue)        cmd.Parameters.Add("@BeanOptionID", dropdown_beans.SelectedValue)        cmd.Parameters.Add("@TortillaOptionID", dropdown_tortilla.SelectedValue)        'Session.Add("FirstName", txtFName.Text)        cmd.ExecuteNonQuery()        cmd = New SqlCommand("Add_EntreeItems", Conn)        cmd.CommandType = CommandType.StoredProcedure        cmd.Parameters.Add("@CateringOrderID", get identity from previous stored proc)   <-------------------------        Dim li As ListItem        Dim p As SqlParameter = cmd.Parameters.Add("@EntreeID", Data.SqlDbType.VarChar)        For Each li In chbxl_entrees.Items            If li.Selected Then                p.Value = li.Value                cmd.ExecuteNonQuery()            End If        Next        Conn.Close()I want to somehow grab the @CateringOrderID that was created as an end product of my first called stored procedure (Add_NewOrder)  and pass that to my second stored procedure (Add_EntreeItems)

View Replies !
Table-valued Function Return Error
 

I have this tsql

Declare @IDtable table(id uniqueidentifier, [Value] varchar(50))

Declare @iDoc Int

exec sp_xml_preparedocument @iDoc Output, @Data

insert into @IDtable(id,[Value])

Select *

From OpenXML(@iDoc, '/listing/Item', 2)

With (Id VarChar(40),

Value varchar(20))

exec sp_xml_removedocument @iDoc

 
but when I tried to right table value function of it so I can use it many place with just change paremeter value like this
 

ALTER FUNCTION [dbo].[splitXMLvalue](@editors xml)

RETURNS @etable table(id uniqueidentifier, [name] varchar(50))

AS

BEGIN





Declare @iDoc Int

exec sp_xml_preparedocument @iDoc Output, @Data

insert into @IDtable(id,[Value])

Select *

From OpenXML(@iDoc, '/listing/Item', 2)

With (Id VarChar(40),

Value varchar(20))

exec sp_xml_removedocument @iDoc

--select id as parentId, [Value] as parentValeu from @IDtable

RETURN

END

 
it gave me this error
 
 

Msg 557, Level 16, State 2, Line 1

Only functions and extended stored procedures can be executed from within a function.

 
can any one help me what I'm doing wrongthanks

View Replies !
Multi-statement Table-Valued Function
I'm creating a Multi-statement Table-Valued Function...
 
Is it possible to insert variables into the table? In other words, is it possible
to have something like
 
declare
@value1 varchar(10)
@value2 varchar(10)
 
BEGIN
<do some work on value1 and value2>
INSERT @returningTable
@value1, @value2
 
instead of
 
BEGIN
<do some work on value1 and value2>
INSERT @returningTable
SELECT col1, col2 from T_SOURCE
 
Here's why I want to insert variables...My function needs to return a table which contains a 'partial' incremental key.
I'll go with an example to explain what i have to do
 
Source_table
col1           col2       
Mike          10
Mike          20
Ben           50
John          15
John          25
John          35
 
The table that my function needs to create should look like this
col1          col2        col3
Mike          10          1
Mike          20          2
Ben           50          1
John          15          1
John          25          2
John          35          3
 
I thought of creating a cursor and then looping through it generate col3 and save values of other individual columns in variables. But don't know how to use those variables when inserting records into function table.
 
Any other ideas? I'm caoming from Oracle world, I might be having some strange ideas on how to solve this problem. Any help is appreciated.
 
Thank you.
 
 

View Replies !
Indexes On Table Variable Of Table Valued Function
Hi there,

Can someone tell me if it is possible to add an index to a Table variable that is declare as part of a table valued function ? I've tried the following but I can't get it to work.

ALTER FUNCTION dbo.fnSearch_GetJobsByOccurrence
(
@param1 int,
@param2 int
)
RETURNS @Result TABLE (resultcol1 int, resultcol2 int)
AS
BEGIN

CREATE INDEX resultcol2_ind ON @Result

-- do some other stuff

RETURN
END

View Replies !
Table-Valued Function Result Vs. Calculation Table
 

I need to return a table of values calculated from other tables. I have about 10 reports which will use approx. 6 different table structures.

Would it be better performance wise to create a physical table in the database to update while calculating using an identity field to id the stored procedure call, return the data and delete the records. For Example:

 DataUserID, StrVal1,Strval2,StrVal4,IntVal1,IntVal2,FloatVal1...

Or using a table-valued function to return a temp table as the result.

I just dont know which overhead is worst, creating a table per function call, or using a defined table then deleting the result set per sp call. 

View Replies !
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?

View Replies !
Performance Of Table-valued Function And Execution Plan
I am using SQL2005 EE with SP1. The server OS is windows 2K3 sp2
 
I have a table-valued function (E.g. findAllCustomer(Name varchar(100), gender varchar(1)) to join some tables and find out the result set base the the input parameters.
 
I have created indexes for the related joinning tables.
 
I would like to check the performance of a table-valued function and optimize the indexing columns by the execution plan.
 
I found the graphic explanation only show 1 icon to represent the function performance. I cannot find any further detail of the function. (E.g. using which index in joinning)
 
If I change the function to stored procedure, I can know whether the T-SQL is using index seek or table scan. I also found the stored procedure version subtree cost is much grether that the table-valued function
 
I would like to know any configureation in management studio can give more inform for the function performance?
 
Thanks
 
 
 

View Replies !
How To Create A Stored Procedure Of This Code (inline Sql In Aspx) ?
I have some SQL code as inline SQL (bad habit, I know). Now I want to convert this to an sproc, but I'm pretty much out of ideas here. The code looks like this:
string SQL = "SELECT * FROM MyDBTable WHERE 1=1";
if (txtMyField1.Text != "")
{
SQL = SQL + " AND MyField1 = @MyField";
}
if (txtMyField2.Text != "")
{
SQL = SQL + " AND MyField2 LIKE '%'+ @MyField2 + '%'";
}
if (txtMyField3.Text != "")
{
SQL = SQL + " AND MyField3 LIKE '%' + @MyField3 + '%'";
}
I have an search page built on ASP.NET 2.0. Based on what the user has entered to the form fields, the SQL in constructed on the fly. Since this is now inside codebehind file (aspx.cs), I want to get rid of it and move it to an sproc. But the question is how ? Some simple SQL clauses are easy to convert to an sproc but this is causing me lots of issues.

View Replies !
Temporary Table Vs. Table Valued Function
I need to return a table of values calculated from other tables. I have about 10 reports which will use approx. 6 different table structures.

Would it be better performance wise to create a physical table in the database to update while calculating using an identity field to id the stored procedure call, return the data and delete the records. For Example:

StrVal1,Strval2,StrVal4,IntVal1,IntVal2,FloatVal1...

Or using a table-valued function to return a temp table as the result.

I just dont know which overhead is worst, creating a table per function call, or using a defined table then deleting the result set per sp call. 

 

View Replies !
Table-valued Function Run Once For Each Row In A Table Variable.
I have a stored produre.  Inside this stored procedure I have table variable with one column.  Once the table variable is populated with rows, I would like to pass each value in the table, into a table-valued function.  The table-valued function may return any number of rows.  I would like all the rows the TVF returns to be returned from the stored procedure as a single result set.  I would also like to do this without defining a table variable to hold the results of the table-value function.
 



Code Snippet

declare @IdTable table
(
 EmployeeId nvarchar( 16 ) not null
)
insert into @IdTable
select EmployeeNumber from Employees
 
/*
I need to run this query for every EmployeeId value in @IdTable and return the results from the stored proc as a single result set.
*/
select * from fn_GetEmployeeById( EmployeeId )

 
 



 
Any help is very much appreciated.
Andrew
 

View Replies !
Table-valued Function Into A @table Variable
In my stored procedure i have a multi-valued varchar(max) parameter and I wrote a table-valued function that takes the varchar(max) and return a table back to the stored procedure where i inserted into a @table. Just wondering is there a better and faster way of doing this?




ALTER   PROCEDURE [dbo].[rpt]

(


@CourtIDs as nvarchar(MAX) -- @CourtIDs = '1231,3432,1234,3421'

)
AS


--split CourtIDs into a table
DECLARE @tbCourtIDs     table(CourtID int NOT NULL PRIMARY KEY)
INSERT INTO @tbCourtIDs
select * from dbo.Split(@CourtIDs, ',')

View Replies !
Table-valued Function Does Not Accept Chinese Characters As Parameter
I have a table-valued function in mssql 2005 as below:
ALTER FUNCTION fn_test{   @test nvarchar(1000)}RETURNS@TEMP TABLE{   test nvarchar(1000)}ASBEGIN   INSERT INTO @TEMP   SELECT @test
   RETURNEND
Everytime, I passed in chinese character (@test), such as æ¸¬é©—, the function will return ????.  What should I do for the table-valued function, so that the chinese character can be passed in?  Please help.
Note: I can search and get the chinese characters if I use stored procedures; and the columns in the tables can store chinese chararcters as well.   Only table-valued function is not working with the chinese characters.  Is it a bug from MSSQL 2005?
 
 

View Replies !
System.DirectoryServices Performance Issue In Table-valued Function
Hi,
I am trying to write a table-valued function in SQL Server 2005 (SP1) to return all active directory groups a user belongs too, using managed code (VB.NET).

Testing the code with a simple winform I get the list of groups in about 0.4 seconds. However the table-valued function takes upwards of 17 seconds to run! Is this normal for managed code in SQL Server?

Imports SystemImports System.TextImports System.DataImports System.Data.SqlClientImports System.Data.SqlTypesImports System.CollectionsImports System.DirectoryServicesImports Microsoft.SqlServer.ServerPartial Public Class UserDefinedFunctions#Region "Constants"    ''' <summary>    ''' The connection string for Active Directory.    ''' </summary>    'Private Const LDAP_CONNECTION_STRING As String = "LDAP://<My LDAP connection string>    ''' <summary>    ''' The LDAP search filter need to find a user in Active Directory.    ''' </summary>    'Private Const LDAP_SEARCH_FILTER_USER As String = "(&(objectclass=user)(objectcategory=person)(sAMAccountName={0}))"#End Region    ''' <summary>    ''' Gets all active directory groups for the user.    ''' </summary>    ''' <returns>All dataset permissions for the user.</returns>    <Microsoft.SqlServer.Server.SqlFunction(DataAccess:=DataAccessKind.None, FillRowMethodName:="udfUserActiveDirectoryGroupsFill", TableDefinition:="GroupID NVARCHAR(100)")> _    Public Shared Function udfUserActiveDirectoryGroups(ByVal userName As String) As IEnumerable        ' Setup the active directory search.        Dim searcher As New DirectorySearcher(LDAP_CONNECTION_STRING)        searcher.Filter = String.Format(LDAP_SEARCH_FILTER_USER, userName)        searcher.SearchScope = SearchScope.Subtree        searcher.PropertiesToLoad.Add("distinguishedname")        ' Run the active directory search.         Dim result As SearchResult = searcher.FindOne()        Dim userEntry As DirectoryEntry = result.GetDirectoryEntry()        Dim userGroups As New ArrayList        GetActiveDirectoryGroupsForEntry(userEntry, userGroups)        Return userGroups    End Function    Public Shared Sub udfUserActiveDirectoryGroupsFill(ByVal source As Object, ByRef GroupID As SqlChars)        GroupID = New SqlChars(CType(source, String))    End Sub    ''' <summary>    ''' Recursively gets the active directory groups for the directory entry.    ''' </summary>    ''' <param name="entry">The active directory entry.</param>    ''' <param name="groups">The list of groups.</param>    Private Shared Sub GetActiveDirectoryGroupsForEntry(ByVal entry As DirectoryEntry, ByVal groups As ArrayList)        For i As Integer = 0 To entry.Properties("memberOf").Count - 1            Dim memberEntry As New DirectoryEntry("LDAP://" + entry.Properties("memberOf")(i).ToString())            groups.Add(memberEntry.Properties("sAMAccountName")(0).ToString())            GetActiveDirectoryGroupsForEntry(memberEntry, groups)        Next    End SubEnd Class

View Replies !
Handling Large Queries In A Table Valued User Defined Function
Hello,

We have created several Table Valued User Defined Functions in a Production SQL Server 2005 DB that are returning large (tens of thousands of) rows obtained through a web service. Our code is based on the MSDN article Extending SQL Server Reporting Services with SQL CLR Table-Valued Functions .

What we have found in our implementations of variations of this code on three seperate servers is that as the rowset grows, the length of time required to return the rows grows exponentially. With 10 columns, we have maxed out at approximately 2 500 rows. Once our rowset hit that size, no rows were being returned and the queries were timing out.

Here is a chart comparing the time elapsed to the rows returned at that time for a sample trial i ran:

Sec /  Actual Rows Returned
0        0
10      237
20      447
30      481
40      585
50      655
60      725
70      793
80      860
90      940
100    1013
110    1081
120    1115
130    1151
140    1217
150    1250
160    1325
170    1325
180    1430
190    1467
200    1502
210    1539
220    1574
230    1610
240    1645
250    1679
260    1715
270    1750
280    1787
290    1822
300    1857
310    1892
320    1923
330    1956
340    1988
350    1988
360    2022
370    2060
380    2094
390    2094
400    2130
410    2160
420    2209
430    2237
440    2237
450    2274
460    2274
470    2308
480    2342
490    2380
500    2380
510    2418
520    2418
530    2451
540    2480
550    2493
560    2531
570    2566

It took 570 seconds (just over 9 1/2 minutes to return 2566 rows).

The minute breakdown during my trial is as follows:
1 = 655   (+ 655)
2 = 1081 (+ 426)
3 = 1325 (+244)
4 = 1610 (+285)
5 = 1822 (+212)
6 = 1988 (+166)
7 = 2160 (+172)
8 = 2308 (+148)
9 = 2451 (+143)

As you can tell, except for a few discrepancies to the resulting row count at minutes 4 and 7 (I will attribute these to timing as the results grid in SQL Management Studio was being updated once every 5 seconds or so), as time went on, fewer and fewer rows were being returned in a given time period. This was a "successful" run as the entire rowset was returned but on more than several occasions, we have reached the limit and have had 0 new rows per minute towards the end of execution.

Allow me to explain the code in further detail:

[SqlFunction(FillRowMethodName = "FillListItem")]
public static IEnumerable DiscoverListItems(...)
{

ArrayList listItems = new ArrayList();

SPToSQLService service = new SPToSQLService();

[...]

DataSet itemQueryResult = service.DoItemQuery(...); // This is a synchronous call returning a DataSet from the Web Service

//Load the DS to the ArrayList


return listItems;
}


public static void FillListItem(object obj, out string col1, out string col2, out string col3, ...)
{

ArrayList item = (ArrayList) obj;


col1 = item.Count > 0 ? (string) item[0] : "";
col2 = item.Count > 0 ? (string) item[1] : "";
col3 = item.Count > 0 ? (string) item[2] : "";
[...]
}

As you will notice, the web service is called, and the DataSet is loaded to an ArrayList object (containing ArrayList objects), before the main ArrayList is returned by the UDF method. There are 237 rows returned within 10 seconds, which leads me to believe that all of this has occured within 10 seconds. The method GetListItems has executed completely and the ArrayList is now being iterated through by the code calling the FillListItem method. I believe that this code is causing the result set to be returned at a decreasing rate. I know that the GetListItems code is only being executed once and that the WebService is only being called once.


Now alot of my larger queries ( > 20 000 rows) have timed out because of this behaviour, and my workaround was to customize my web service to page the data in reasonable chunks and call my UDF's in a loop using T-SQL. This means calling the Web Service up to 50 times per query in order to return the result set.

Surely someone else who has used Table Valued UDFs has come accross this problem. I would appreciate some feedback from someone in the know, as to whether I'm doing something wrong in my code, or how to optimize an SQL Server properly to allow for better performance with CLR functions.

Thanks,

Dragan Radovic

View Replies !
Stored Procedure Using A Declared Variable In Insert Query (inline Or Using EXEC)
Hello,

I have a stored procedure where I run an insert statement.  I want to knwo if it is possible to do it using a variable for the table name (either in-line or with an EXEC statement without building a string first and executing that string.  See examples of what I am talking about in both cases below:

I want to be able to do this (with or without the EXEC) :
------------------------------------------------------------------------------------

DECLARE @NewTableNameOut  as varchar(100)


Set @NewTableNameOut  = 'TableToInsertInto'


EXEC(
                Insert Into @NewTableNameOut
                Select * From tableToSelectFrom
            )

------------------------------------------------------------------------------------

I can not do the above because it says I need to declare/set the @NewTableNameOut variable (assuming it is only looking at this for the specific insert statement and not at the variable I set earlier in the stored procedure.


I can do it like this by creating a string with the variable built into the string and then executing the string but I want to know if I can do it like I have listed above.

------------------------------------------------------------------------------------

DECLARE @NewTableNameOut  as varchar(100)


Set @NewTableNameOut  = 'TableToInsertInto'


EXEC(
                'Insert Into ' + @NewTableNameOut + ' ' +
                'Select * From tableToSelectFrom'
            )

------------------------------------------------------------------------------------



It is not an issue for my simple example above but I have some rather large queries that I am building and I want to run as described above without having to build it into a string. 

Is this possible at all?

If you need more info please let me know.

View Replies !
SqlDataSource And Stored Procedure Not Getting Called
Im using a SqlDataSource control. Ive got my "selectcommand" set to the procedure name, the "selectcommandtype" set to "storedprocedure"What am i doing wrong ?  Ive got a Sql 2005 trace window open and NO sql statements are coming through  "ds" runat="server" ConnectionString="&lt;%$ ConnectionStrings:myConnectionString %>" SelectCommand="my_proc_name" SelectCommandType="StoredProcedure">

"txtF1" Name="param1" Type="String" />
"txtF2" Name="param2" Type="String" />
"" FormField="txtF3" Name="param3" Type="String" />
"" FormField="txtF4" Name="param4" Type="String" />



  

View Replies !
Stored Procedure Called From Access97
I have a project that uses an Access97 front end to call a SQL 6.5 stored procedure. The stored procedure BCPs orders to a text file and copies it to a particular server.

All works fine if I log into my ODBC/SQL connection as "SA" but if I don't, I received errors saying only the owner or system administrator can execute XP_CMDSHELL, etc.

I have tried to hard code the SA account in my database connection string but it doesn't help. I am using qdf.execute to execute my SQL string which is qdf.sql = "execute <procedure name>"

Any suggestions appreciated.

Thanks,
-Darin.

View Replies !
Is The Transaction Context Available Within A 'called' Stored Procedure For A Transaction That Was Started In Parent Stored Procedure?
I have  a stored procedure 'ChangeUser' in which there is a call to another stored procedure 'LogChange'. The transaction is started in 'ChangeUser'. and the last statement in the transaction is 'EXEC LogChange @p1, @p2'. My questions is if it would be correct to check in 'LogChange' the following about this transaction: 'IF @@trancount >0 BEGIN Rollback tran' END Else BEGIN Commit END.
 Any help on this would be appreciated.

View Replies !
Update Stored Procedure Not Working When Called From C#
OK, I have been raking my brains with this and no solution yet. I simply want to update a field in a table given the record Id. When I try the SQL in standalone (no sp) it works and the field gets updated. When I do it by executing the stored procedure from a query window in the Express 2005 manager it works well too. When I use the stored procedure from C# then it does not work:
 1. ExecuteNonQuery() always returns -1 2. When retrieving the @RETURN_VALUE parameter I get -2, meaning that the SP did not find a matching record.
So, with #1 there is definitely something wrong as I would expect ExecuteNonQuery to return something meaningful and with #2 definitely strange as I am able to execute the same SQL code with those parameters from the manager and get the expected results.
Here is my code (some parts left out for brevity):1 int result = 0;
2 if (!String.IsNullOrEmpty(icaoCode))
3 {
4 icaoCode = icaoCode.Trim().ToUpper();
5 try
6 {
7 SqlCommand cmd = new SqlCommand(storedProcedureName);(StoredProcedure.ChangeAirportName);
8 cmd.Parameters.Add("@Icao", SqlDbType.Char, 4).Value = newName;
9 cmd.Parameters.Add("@AirportName", SqlDbType.NVarChar, 50).Value = (String.IsNullOrEmpty(newName) ? null : newName);
10 cmd.Parameters.Add("@RETURN_VALUE", SqlDbType.Int).Direction = ParameterDirection.ReturnValue;
11 cmd.Connection = mConnection; // connection has been opened already, not shown here
12 cmd.CommandType = CommandType.StoredProcedure;
13 int retval = cmd.ExecuteNonQuery(); // returns -1 somehow even when RETURN n is != -1
14 result = (int)cmd.Parameters["@RETURN_VALUE"].Value;
15
16 }
17 catch (Exception ex)
18 {
19 result = -1;
20 }
21 }

 And this is the stored procedure invoked by the code above:1 ALTER PROCEDURE [dbo].[ChangeAirfieldName]
2 -- Add the parameters for the stored procedure here
3 @Id bigint = null,-- Airport Id, OR
4 @Icao char(4) = null,-- ICAO code
5 @AirportName nvarchar(50)
6 AS
7 BEGIN
8 -- SET NOCOUNT ON added to prevent extra result sets from
9 -- interfering with SELECT statements.
10 SET NOCOUNT ON;
11
12 -- Parameter checking
13 IF @Id IS NULL AND @Icao IS NULL
14 BEGIN
15 RETURN -1;-- Did not specify which record to change
16 END
17 -- Get Id if not known given the ICAO code
18 IF @Id IS NULL
19 BEGIN
20 SET @Id = (SELECT [Id] FROM [dbo].[Airports] WHERE [Icao] = @Icao);
21 --PRINT @id
22 IF @Id IS NULL
23 BEGIN
24 RETURN -2;-- No airport found with that ICAO Id
25 END
26 END
27 -- Update record
28 UPDATE [dbo].[Airfields] SET [Name] = @AirportName WHERE [Id] = @Id;
29 RETURN @@ROWCOUNT
30 END

 As I said when I execute standalone UPDATE works fine, but when approaching it via C# it returns -2 (did not find Id).

View Replies !
How To Check When A Stored Procedure Was Last Called/executed
HiOur SQL server has a lot of stored procedures and we want to get somecleaning up to be done. We want to delete the ones that have been notrun for like 2-3 months. How exactly will i find out which ones todelete. Enterprise manager only seesm to give the "Create Date"How exactly can I find the last called date ! I guess you could write aquery for that ! but how ???P.S I dont want to run a trace for 1 months and see what storedprocedures are not being used.

View Replies !
DTS Package Failing On Called Stored Procedure
I am executing a DTS package that I did not create. it is failing on a step titled 'transpose to staging table' and it is failing when calling this stored procedure: :
exec usp_transpose_ilisa
This is the error:

Step 'DTSStep_DTSExecuteSQLTask_5' failed
Step Error Source: Microsoft OLE DB Provider for SQL Server
Step Error Description:The statement has been terminated. (Microsoft OLE DB Provider for SQL Server (80040e57): String or binary data would be truncated.)
Step Error code: 80040E57
Step Error Help File:
Step Error Help Context ID: 0

I am able to execute the code from the stored procedure in query analyzer with NO errors ..be it fails when called by the package.....Can anyone help!! (the code from the stored procedure is below)


CREATE PROCEDURE usp_transpose_ilisa AS
DECLARE @firstrow VARCHAR(256)
SELECT @firstrow = a FROM temptry WHERE recid = 1
DECLARE cur_transpose CURSOR FOR
SELECT recid, a, b
FROM temptry
WHERE recid > 1
ORDER BY recid
DECLARE @temprecid INT
DECLARE @tempa VARCHAR(256)
DECLARE @tempb VARCHAR(256)
DECLARE @tempc VARCHAR(256)
DECLARE @tempd VARCHAR(256)
DECLARE @cur_group VARCHAR(256)
DECLARE @nextrecid INT
INSERT INTO trytext (recid, biz_type, distance, [name], addy, phone)
VALUES (1,'X',999.9,@firstrow,'X','X')
OPEN cur_transpose
FETCH NEXT FROM cur_transpose
INTO @temprecid, @tempa, @tempb
WHILE @@FETCH_STATUS = 0
BEGIN
IF @tempa IN ('Archery Equipment & Supplies',
'Archery Ranges',
'Auto Dealers',
'bicycle',
'Bicycle Dealers',
'Bicycle Repair & Maintenance',
'Bicycles',
'Boat & Yacht Charters/Rent/Lease',
'Boat Dealers',
'Boat Service & Repair',
'Campgrounds & RV Parks',
'Camping Equipment & Supplies',
'Canoes & Kayaks',
'Computer & Equipment Dealers',
'Diving Equipment & Supplies',
'Diving Instruction',
'electronic',
'Electronics',
'Exercise & Fitness Classes',
'Exercise & Fitness Equipment',
'Fishing Bait & Tackle',
'Fishing Guides Charters & Parties',
'Guns & Ammunition',
'health clubs & gyms',
'Horse Dealers',
'Horse Stables',
'Horse Trainers',
'Horseback Riding',
'Photographic Equipment & Supplies',
'riding academies & schools',
'RV & Camper Dealers',
'RV & Camper Rent & Lease',
'Skates, Skateboards & Rollerblades',
'Skating Equipment & Supplies',
'Ski Clothing, Equipment & Supplies',
'Ski Equipment Clothing & Supplies',
'Ski Equipment Rental',
'Ski Instruction',
'Ski Resorts',
'sporting goods',
'Taxidermists',
'Travel Agents')
SET @cur_group = @tempa
ELSE
IF @tempa LIKE '%_._'
BEGIN
SELECT @nextrecid = MIN(recid)
FROM temptry
WHERE recid > @temprecid
SELECT @tempc = a
FROM temptry
WHERE recid = @nextrecid
SELECT @tempd = a
FROM temptry
WHERE recid = (SELECT MIN(recid) FROM temptry WHERE recid > @nextrecid)
IF @tempc LIKE '(%'
BEGIN
SET @tempd = @tempc
SET @tempc = 'no address listed'
END
IF @tempd NOT LIKE '(%'
SET @tempd = 'no phone listed'
INSERT INTO trytext (recid, biz_type, distance, [name], addy, phone)
VALUES (@temprecid, @cur_group, @tempa, @tempb, @tempc, @tempd)
END
FETCH NEXT FROM cur_transpose
INTO @temprecid, @tempa, @tempb
END
CLOSE cur_transpose
DEALLOCATE cur_transpose
GO

View Replies !
Why Is It Called Stored Procedure Instead Of Stored Sets?
Since RDMBS and its language SQL is set-based would it make more senseto call a given stored process "Stored Sets" instead of currenttheorically misleading Stored Procedure, as a measure to prodprogrammers to think along the line of sets instead of procedure?

View Replies !
Error With Multi-Valued Report Parameter Using Stored Procedure
Hi All,
I'm unable to run the report the report with multi-valued parameter using the below StoredProcedure as dataset:
 
CREATE PROCEDURE spprodsales
@productid  int

AS

select SalesOrderID,OrderQty,UnitPrice,ProductID

FROM Sales.SalesOrderDetail

Where ProductID IN (@productid)

RETURN

 
And when I'm replacing this dataset  to a query as below I'm able to run the report with multiple values selected for productid parameter :

select SalesOrderID,OrderQty,UnitPrice,ProductID

FROM Sales.SalesOrderDetail

Where ProductID IN (@productid)
 
So, can anyone please help me out possibly using the same stored procedure as above.
 
Thanks,
Kripa
 

View Replies !
How To Get The Output Parameter From An Internally Called Stored Procedure???
Hi all,i have a problem and couldnt find anything even close  to it. please help me, here is the description of what i m trying to accomplish:I have a trigger that is generating a column value and calling a stored procedure after the value is generated. And this stored procedure is setting this generated value as an output parameter. But my problem is:my asp.net page is only sending an insert parameter to the table with the trigger, trigger is running some code depending on the insert parameter and calling this other stored procedure internally. So basically i m not calling this last stored procedure that sets the output parameter within my web form. How can i get the output parameter in my webform? Everthing is working now, whenever an insert hits the table trigger runs and generates this value and called stored procedure sets it as an output parameter. I can get the output parameter with no problem in query analyzer, so the logic has no problem but i have no idea how this generated output parameter can be passed in my webform since its not initiated there.any help will greately be appreciated, i m sure asp.net and sql server 2000 is powerful and flexible enough to accomplish this but how??-shane

View Replies !
Gettings Warnings Sent From A Stored Procedure Called With Jdbc
When running a stored procedure, how can i retrieve the warnings that are issued within the stored procedure?

the code used is below,

the jdbc is connecting fine, it is running the stored procedure, but when an error is raised in the stored procedure, it is not coming back into s.getwarnings()
warning raised in stored proc with





Code Block

RAISERROR ('Error', 16, 1)with nowait;

there are no results for the stored procedure, I am just wanting to get the warnings






Code Block

Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

Connection con = DriverManager.getConnection("jdbc:sqlserver://localh...........);


       
CallableStatement s = con.prepareCall("{call procedure_name}");

s.execute();



//running in seprate thread

            SQLWarning warn = s.getWarnings();
            while (m.running) {
                if(warn == null) {
                    warn = s.getWarnings();
                }
                safeOut(warn);
                if(warn != null)
                    warn = warn.getNextWarning();
                m.wait(100);
               
            }the code is not complete, but should show what is happening

it is continually outputting null for the warning, though the strored proc is definately raising errors, which is proven by running it in a query window in sql server.

it is retreiving warning if the statement is a raiseerror instead of a call to the proc





Code Block

CallableStatement s = con.prepareCall("RAISERROR ('Error', 1, 1)with nowait;");

this thread is quite related, but doesnt offer a working solution
Getting messages sent while JDBC Driver calls stored procedure


any help much appreciated,

thankyou
Simon

View Replies !
Debugging A CLR Stored Procedure That Is Being Called From An SSIS Package
I need help debugging a CLR stored procedure that is being called from an SSIS package. I can debug the procedure itself from within Visual Studio by using "Step into stored procedure" from Server Explorer, but really need to debug it as it is being called from SSIS.

View Replies !
Debugging A CLR Stored Procedure That Is Being Called From An SSIS Package
 
I need help debugging a CLR stored procedure that is being called from an SSIS package. I can debug the procedure itself from within Visual Studio by using "Step into stored procedure" from Server Explorer, but really need to debug it as it is being called from SSIS.

 

View Replies !
Dynamic Security Stored Procedure Repeatedly Called
I have implemented an SSAS stored procedure for dynamic security and I call this stored procedure to obtain the allowed set filter. To my supprise, the stored procedure is being called repeatedly many times (more than 10) upon establishing the user session. Why is this happening?

View Replies !
Managed Stored Procedure Not Executing When Called Programmatically
I have created a managed stored procedure in C# tha returns rows of data, based on a couple of input parameters.  Stored procedure has been registered with SQL server.

Using the Dataset designer in VS2005, I added a new query to my table adapter.  The query basically executes the stored procedure registered in the database.

From the Dataset designer, the query works fine and returns data as expected.  However, when I execute the stored procedure within code, using an instance of my table adapter,  I get no data.

I call my stored procedure using the following statement:

DataTable closeRangePOIs = tableAdapter.GetCloseRangePOIs(x1, y1);

The stored procedure, GetCloseRangePOIs(),  of my table adapter is not being executed.  Any tips on what I should be looking for?

TIA.

Klaus

View Replies !
Stored Procedures Vs. Table-Valued Functions
Hi everyone.I'd like to know how stored procedures and table-valued functions compare when it comes to returning a resultant set of data. I know there is a link somewhere but I can't immediately find it.Thanks.

View Replies !
Identifying Results Sets When Stored Procedure Called Multiple Times
I have a report based on our product names that consists of two parts.Both insert data into a temporary table.1. A single grouped set of results based on all products2. Multiple tables based on individual product names.I am getting data by calling the same stored procedure multipletimes... for the single set of data I use "product like '%'"To get the data for individual products, I am using a cursor to parsethe product list.It's working great except that I have no idea how to identify theresults short of including a column with the product name. While thatis fine, I'm wondering if there is something that is like a header ortitle that I could insert prior to generating the data that would looka little tighter.Thanks in advance-DanielleJoin Bytes!

View Replies !
Differences Between SQL Stored Procedures And Table-valued Functions
I am a bit confused by the difference between a stored procedure and a table-valued function.  Can somebody please either give me a simple explanation, or point me at something I can read.

I thought I had it worked out, and had coded some action queries as stored procedures, and I wrote a table-valued function that was effectively an encapsulated SELECT so that SELECT * FROM Spouse(@ID) worked fine.   Then I wanted to use a function SpousePair, that was similar to Spouse, to power a Gridview.  I discovered that I couldn't.  It seems that a SQLDataSource requires either a SELECT statement or a stored procedure.  So I wrote a stored procedure SpousePair(@ID1, @ID2).

I find that whereas I tested Spouse with
         SELECT * FROM SPOUSE(@ID)
I tested SpousePair with
         EXEC SpousePair @ID1 @id2

Now I want to combine these: if I could I would write
         SELECT * FROM SPOUSE(@ID) WHERE SPOUSEID NOT IN
                 (SELECT SPOUSEID FROM SpousePair(@ID1, @ID2))

However this is invalid because you can't put a stored procedure in a Select statement, and SELECT .... NOT IN (EXEC SpousePair @ID1 @ID2) is also invalid.

Is there any alternative to creating a table-valued function, SpousePairA, that is identical to SpousePair but coded as a function.  I'm reluctant to do this because then I'll have two bits of quite complicated SQL logic to maintain.

View Replies !

Copyright © 2005-08 www.BigResource.com, All rights reserved