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.





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 Complete Forum Thread with Replies

Related Forum Messages:
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 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 !
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 !
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 !
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 !
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 UDF With Conditional RETURN
I'm getting syntax errors that just aren't helping me at all, so I thought maybe what I'm trying to do can't be done. I'm creating a UDF with 4 parameters, and I want it to return a result set (i.e. a table). But I want a different result set depending upon the value of one of the parameters. This works totally fine as a SP, but I can't tell where to put the RETURN clause(s) on the UDF.
I've got:
CREATE FUNCTION myFunction(@param1,...,@param4)
RETURNS TABLE
AS
BEGIN
IF @param1='x'
BEGIN
RETURN(SELECT columns FROM TableX)
END
ELSE
BEGIN
RETURN(SELECT columns FROM TableY)
END
END
I get an "Incorrect syntax near the keyword 'IF'" error. I also tried using just one RETURN() wrapped around the outside of the IF construction (right after the very first BEGIN and before the last END), but to no avail. I get no errors when I run this logic as an SP. Is this type of construct not allowed in a UDF? Is there an alternative? I can't just leave this as a proc because I'm going to have to call these results from several views. Help!

Thanks,
-Ed H.

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 !
Table Valued Functions - Yield Return Error
So I was creating a new table-valued function today which queries some data from a preexisting table.  Since this is my first table-valued function, I decided to check out some of the examples and see what I can figure out.

One particular example helped me out a bit until I ran into some data access issues...
http://msdn2.microsoft.com/en-us/library/ms165054.aspx

So I create my function:

[SqlFunction(DataAccess = DataAccessKind.Read,SystemDataAccess=SystemDataAccessKind.Read,FillRowMethodName = "FillMyRow",TableDefinition ="p1 int, p2 int"]
public static IEnumerable getMyTable()
{
    using (SqlConnection conn = ....)
    {
        using (SqlCommand command = conn.CreateCommand())
        {
            ///.... populate command text, open connection
            using (SqlDataReader rdr = command.ExecuteReader())
            {
                while (rdr.Read())
                {
                    customObject1 o = new customObject1();
                    ///... populate o's parameters from reader ...
                    yield return o;
                }
        }
    }
}


public static void FillMyRow(
object source,
out int p1,
out int p2)
{
    customObject1 f = (customObject1)source;
    p1 = f.p1;
    p2 = f.p2;
}

Notice, this example yield returns the value o upon each iteration of the reader.
Despite the fact that the DataAccess is set to Read I still get the error...

An error occurred while getting new row from user defined Table Valued Function :

System.InvalidOperationException: Data access is not allowed in this context. Either the context is a function or method not marked with DataAccessKind.Read or SystemDataAccessKind.Read, is a callback to obtain data from FillRow method of a Table Valued Function, or is a UDT validation method.

I did however get past this error, by creating a collection of customObject1, populated it within the while(rdr.Read()) loop, then return the collection after closing the connection, command and reader.

I assume this error has something to do with the fact that you can't yield return results from within an open reader.  Is this error right though in this case?  Whats causing it to throw a InvOp Exception? Or is this a bug?

Thanks for the attention.

View Replies !
Stored Procedure To Copy Table 1 To Table 2 Appending The Data To Table 2.
Just wondering if there is an easy transact statement to copy table 1 to table 2, appending the data in table 2.with SQL2000, thanks.

View Replies !
Assign Function To Table Var??
I keep getting a declare error on this:
DECLARE @SplitTable TABLE(Idx BIGINT IDENTITY(1,1), SplitData VARCHAR(20), Size INT)
SET @SplitTable = dbo.SplitToTable('|', '1|One|0:26:20|541|abc|xxx|6:26:33|21705')

All I want to do is assign the table that my function returns to a variable. Should be easy, but I tried the above and assigning with 'as':

select * from dbo.SplitToTable('|','1|One|0:26:20|541|abc|xxx|6:26:33|21705') as Split

that didn't work either.

Also tried:
DECLARE @SplitTable TABLE(Idx BIGINT IDENTITY(1,1), SplitData VARCHAR(20), Size INT)
select @SplitTable= from dbo.SplitToTable('|','1|One|0:26:20|541|abc|xxx|6:26:33|21705')

what am I missing?

--PhB

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 !
Stored Procedure To Return Table?
Hi,Am new to Stored Procedures and am lost how to achieve the following. I havethis table:-CREATE TABLE [dbo].[docs] ([ID] [int] IDENTITY (1, 1) NOT NULL ,[ParentID] [int] NULL ,[Name] [varchar] (50) COLLATE Latin1_General_CI_AS NULL ,[Link] [varchar] (100) COLLATE Latin1_General_CI_AS NULL) ON [PRIMARY]GOI want to write a stored procedure to return a single column table. Thefirst field should contain the result of:SELECT ParentID WHERE ID = @id@id being the procedure input parameter.The procedure should then iterate through the table returning subsequent(single column) rows containing the result of:SELECT ParentID WHERE ID = @PreviousRowParentIDUntil NULL is returnedCan anyone help?Thanks,Jack

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 !
Creating A Stored Procedure That Will Summarize Data In A Table Into A Table Reflecting Period Data Using An Array Type Field
I am attempting to create a stored procedure that will launch at report runtime to summarize data in a table into a table that will reflect period data using an array type field.  I know how to execute one line but I am not sure how to run the script so that it not only summarizes the data below but also creates and drops the table.
 
Any help would be greatly appreciated.
 
Current Table
 
Project   |  Task      | Category |  Fiscal Year | Fiscal Month | Total Hours
---------------------------------------------------------------------------------------------------------
Proj 1     |  Task 1   | Cat 1      |  2007           |  01                |   40
Proj 1     |  Task 1   | Cat 2      |  2007           |  02                |   20
Proj 1     |  Task 1   | Cat 3      |  2007           |  03                |   35
Proj 1     |  Task 1   | Cat 1      |  2008           |  01                |   40
Proj 1     |  Task 1   | Cat 2      |  2008           |  02                |   40
Proj 1     |  Task 1   | Cat 3      |  2008           |  03                |   40
 
Proposed Table
 
Project   | Task      | Category   | Fiscal Month 01   | Fiscal Month 02   | Fiscal Month 03 | Fiscal Year
---------------------------------------------------------------------------------------------------------------------------------------------------
Proj 1     |  Task 1  | Cat 1        |          40              |           0               |         0              |    2007
Proj 1     |  Task 1  | Cat 2        |           0               |         20               |         0              |    2007Proj 1     |  Task 1  | Cat 3        |           0               |           0               |        35             |    2007
Proj 1     |  Task 1  | Cat 1        |         40               |           0               |          0             |    2008

Proj 1     |  Task 1  | Cat 2        |           0               |         40               |          0             |    2008
Proj 1     |  Task 1  | Cat 3        |           0               |           0               |        40             |    2008
 
Thanks,
Mike Misera

View Replies !
Stored Procedure To Return All Rows In A Table
Hi there,I need to create a stored procedure almost like "Current_user()" to returnto me the total rows in a table.. Is this possible? plz helpRudi

View Replies !
How Return Table Varibles By Stored Procedure
Can We return Table Varibles
Using OUTPUT VARIABLES OR ANY OTHER SOLUTION's.
Pls Sir Help Me

Yaman

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 !
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 !
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 !
Using Return X In A Stored Procedure Doesn't Work With Table Adapters
Hi,

I was trying to create a simple SP that return a single value as follows:CREATE PROCEDURE IsListingSaved@MemberID INT,@ListingID INTASIF EXISTS (SELECT [Member_ID] FROM [Member_Listing_Link] WHERE [Member_ID] = @MemberID AND [Listing_ID] = @ListingID)    Return 1ELSE    Return 0GOWhen I try it out in the Tableadapter's preview table, I get the correct result (1, where the entries exist). However, in the BLL, I tried to get the value as:Dim intResult as IntegerintResult = CType(Adapter.IsListingSaved(intMemberID, intListingID), Integer). However, this always returns 0 (when it should be returning 1). P.S. Curiously, breakpoints skipped the VS generated code for the adapter. What could be the problem? Thanks,Wild Thing 

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 !
Return NULL From A CLR Scalar-Valued Function
Hi,

 

I have an assembly that contains the following function:

 

Public Class Lookup

 

<SqlFunction()> _

Public Shared Function MyTest() As Integer

Return System.Data.SqlTypes.SqlInt64.Null

End Function

 

End Class

 

Then in SSMS:

 

CREATE ASSEMBLY IRS_MyTest

FROM '\machine empmyAssembly.dll'

GO

CREATE FUNCTION dbo.MyTest() RETURNS INT

AS EXTERNAL NAME IRS_MyTest.[MyClass].MyTest

GO

 

when I run:

 

SELECT dbo.MyTest()

 

the following is returned:

 

Msg 6522, Level 16, State 2, Line 1

A .NET Framework error occurred during execution of user defined routine or aggregate 'MyTest':

System.Data.SqlTypes.SqlNullValueException: Data is Null. This method or property cannot be called on Null values.

System.Data.SqlTypes.SqlNullValueException:

at System.Data.SqlTypes.SqlInt64.get_Value()

at System.Data.SqlTypes.SqlInt64.op_Explicit(SqlInt64 x)

at Informed.DCLG.IRS.SQL.IncidentTransform.Lookup.MyTest()

 

 

Can anyone please advise on how to return back a null value.  Currently, my only other option is to return nothing (actually returns 0) and then wrap this up to convert the value to null - not ideal.

 

 

 

Thanks,

 

Jan.

View Replies !
How Can I Assign A Stored Procedure As Cursor's Data Source In AStored Procedure?
How can I create a Cursor into a Stored Procedure, with another Stored Procedure as data source?
 
Something like this:
 
CREATE PROCEDURE TestHardDisk
AS
BEGIN

DECLARE CURSOR HardDisk_Cursor
FOR Exec xp_FixedDrives
   -- The cursor needs a SELECT Statement and no accepts an Stored Procedure as Data Source
 
OPEN CURSOR HardDisk_Cursor

 
FETCH NEXT FROM HardDisk_Cursor
INTO @Drive, @Space

WHILE @@FETCH_STATUS = 0
BEGIN

...
END
END

View Replies !
Stored Procedure For Insert Data From One Table To Another Table
Hi,
     I am having 2 tables. One is main table and another is history table. Whenever I update the main table, I need to insert the all the main table data to History table, before updating the main table.
Overall it is like storing the history of the table updation.
How do i write a stored procedure for this?
Anybody has done this before?
Pls help me.
 

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 !
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 !
What Is The Difference Between: A Table Create Using Table Variable And Using # Temporary Table In Stored Procedure
 which is more efficient...which takes less memory...how is the memory allocation done for both the types.

View Replies !
&&"Must Declare The Scalar Variable&&" In Table-valued Function
Hi, I'm having trouble with this multi-statement table-valued function:

ALTER FUNCTION MakeArDetail
(
    -- Add the parameters for the function here
    @dateStart DATETIME,
    @dateEnd DATETIME
)
RETURNS @arDetail TABLE 
(   
     Insurer VARCHAR(50),
     NABP INT DEFAULT 0,
     Claim MONEY DEFAULT 0,
     Payment MONEY DEFAULT 0,
     NumRx CHAR(7),
     PatientName VARCHAR(50),
     Paid030 MONEY DEFAULT 0,
     Paid3160 MONEY DEFAULT 0,
     Paid6190 MONEY DEFAULT 0,
     Paid91120 MONEY DEFAULT 0,
     Paid121 MONEY DEFAULT 0
)
AS
BEGIN
DECLARE @arTemp TABLE
(   
     Insurer VARCHAR(50),
     NABP INT DEFAULT 0,
     Claim MONEY DEFAULT 0,
     Payment MONEY DEFAULT 0,
     NumRx CHAR(7),
     PatientName VARCHAR(50),
     Paid030 MONEY DEFAULT 0,
     Paid3160 MONEY DEFAULT 0,
     Paid6190 MONEY DEFAULT 0,
     Paid91120 MONEY DEFAULT 0,
     Paid121 MONEY DEFAULT 0
)

INSERT INTO @arTemp
   SELECT DISTINCT Insurer,NABP,0,0,NumRx,Patient,0,0,0,0,0 FROM Pims;
UPDATE @arTemp SET Claim =
  (SELECT SUM(Pims.AmtReq)
       FROM Pims
       WHERE Pims.Insurer = @arTemp.Insurer AND
             Pims.NABP = @arTemp.NABP AND
             Pims.NumRx = @arTemp.NumRx
  );

INSERT INTO @arDetail SELECT * FROM @arTemp
RETURN
END
GO

I get
Msg 137, Level 15, State 2, Procedure MakeArDetail, Line 43
Must declare the scalar variable "@arTemp".

I don't understand why SQL thinks @arTemp is a scalar variable which has to be declared.
If I don't include the UPDATE command the thing works.

View Replies !
Table Return Function
Dear all,
can i write a table return function like this?

create function my_function(
returns @MYTABLE table(NAME VARCHAR(20),SES VARCHAR(20),CNT DECIMAL(10),MYDATE DATATIME)
insert into @mytable
select col1,col2,col3,col4 from tab1
go
select col1,col2,col3,col4 from tab2
go
select col1,col2,col3,col4 from tab3
go
select col1,col2,col3,col4 from tab4
go
return
end


am i doing correct?
what i'm expecting from this function is, i need all the data from select statements should be inserted into one table.
please guide me in this regard


Vinod
Even you learn 1%, Learn it with 100% confidence.

View Replies !
Query To Return Records Where One Table Is Void Of Linked Data In Another Table
I have two tables that share a common identity row.  I need to build a query where data that exists in one table does not contain data in the other table.  For example, table 1 has columns of Owner_ID, LastName, FirstName and table 2 has columns Auto_ID, Owner_ID, AutoMake.  Both tables are joined by the Owner_ID column.  I need a query that provides all owners from table 1 who do not have an entry in table 2.
 
Thanks in advance,
 
Mark

View Replies !
Table-valued User-defined Function: Commands Completed Successfully, Where Is The Result? How Can I See Output Of The Result?
Hi all,
 
I copied the following code from Microsoft SQL Server 2005 Online (September 2007):
UDF_table.sql:

USE AdventureWorks;

GO

IF OBJECT_ID(N'dbo.ufnGetContactInformation', N'TF') IS NOT NULL

DROP FUNCTION dbo.ufnGetContactInformation;

GO

CREATE FUNCTION dbo.ufnGetContactInformation(@ContactID int)

RETURNS @retContactInformation TABLE

(

-- Columns returned by the function

ContactID int PRIMARY KEY NOT NULL,

FirstName nvarchar(50) NULL,

LastName nvarchar(50) NULL,

JobTitle nvarchar(50) NULL,

ContactType nvarchar(50) NULL

)

AS

-- Returns the first name, last name, job title, and contact type for the specified contact.

BEGIN

DECLARE

@FirstName nvarchar(50),

@LastName nvarchar(50),

@JobTitle nvarchar(50),

@ContactType nvarchar(50);

-- Get common contact information

SELECT

@ContactID = ContactID,

@FirstName = FirstName,

@LastName = LastName

FROM Person.Contact

WHERE ContactID = @ContactID;

SELECT @JobTitle =

CASE

-- Check for employee

WHEN EXISTS(SELECT * FROM HumanResources.Employee e

WHERE e.ContactID = @ContactID)

THEN (SELECT Title

FROM HumanResources.Employee

WHERE ContactID = @ContactID)

-- Check for vendor

WHEN EXISTS(SELECT * FROM Purchasing.VendorContact vc

INNER JOIN Person.ContactType ct

ON vc.ContactTypeID = ct.ContactTypeID

WHERE vc.ContactID = @ContactID)

THEN (SELECT ct.Name

FROM Purchasing.VendorContact vc

INNER JOIN Person.ContactType ct

ON vc.ContactTypeID = ct.ContactTypeID

WHERE vc.ContactID = @ContactID)

-- Check for store

WHEN EXISTS(SELECT * FROM Sales.StoreContact sc

INNER JOIN Person.ContactType ct

ON sc.ContactTypeID = ct.ContactTypeID

WHERE sc.ContactID = @ContactID)

THEN (SELECT ct.Name

FROM Sales.StoreContact sc

INNER JOIN Person.ContactType ct

ON sc.ContactTypeID = ct.ContactTypeID

WHERE ContactID = @ContactID)

ELSE NULL

END;

SET @ContactType =

CASE

-- Check for employee

WHEN EXISTS(SELECT * FROM HumanResources.Employee e

WHERE e.ContactID = @ContactID)

THEN 'Employee'

-- Check for vendor

WHEN EXISTS(SELECT * FROM Purchasing.VendorContact vc

INNER JOIN Person.ContactType ct

ON vc.ContactTypeID = ct.ContactTypeID

WHERE vc.ContactID = @ContactID)

THEN 'Vendor Contact'

-- Check for store

WHEN EXISTS(SELECT * FROM Sales.StoreContact sc

INNER JOIN Person.ContactType ct

ON sc.ContactTypeID = ct.ContactTypeID

WHERE sc.ContactID = @ContactID)

THEN 'Store Contact'

-- Check for individual consumer

WHEN EXISTS(SELECT * FROM Sales.Individual i

WHERE i.ContactID = @ContactID)

THEN 'Consumer'

END;

-- Return the information to the caller

IF @ContactID IS NOT NULL

BEGIN

INSERT @retContactInformation

SELECT @ContactID, @FirstName, @LastName, @JobTitle, @ContactType;

END;

RETURN;

END;

GO

----------------------------------------------------------------------
I executed it in my SQL Server Management Studio Express and I got: Commands completed successfully. I do not know where the result is and how to get the result viewed.  Please help and advise.
 
Thanks in advance,
Scott Chang
 

View Replies !
SQL2K SP4 Gives Error 1706 Creating Multi-statement Table-valued Function Names Beginning With &&"sys&&"?
Hi all,
 
I've created a number of tables, views, sproc, and functions whose names begin with "sys_", but when I tried to create a multi-statement table-valued function with this type of name, I got:
 
Server: Msg 1706, Level 16, State 2, Procedure sys_tmp, Line 9
System table 'sys_test' was not created, because ad hoc updates to system catalogs are not enabled.
 
I had a quick look in this forum for 1706 (and on Google) but couldn't find anything.  Does anyone know for certain if this is a bug in SQL2K?
 
Thanks, Jos
 
Here's a test script:
/*
----------------------------------------------------------------------------------------------------
T-SQL code to test creation of three types of function where the function name begins with "sys_".
Jos Potts, 02-Nov-2006
----------------------------------------------------------------------------------------------------
*/
 
PRINT  @@VERSION
go
 
PRINT  'Scalar function with name "sys_" creates ok...'
go
 
CREATE FUNCTION sys_test
       ()
RETURNS       INT
AS
BEGIN
       RETURN 1
END
go
 
DROP   FUNCTION sys_test
go
 
PRINT  ''
go
 
 
PRINT  'In-line table-valued function with name "sys_" creates ok...'
go
 
CREATE FUNCTION sys_test
       ()
RETURNS       TABLE
AS
RETURN SELECT 1      c
go
 
DROP   FUNCTION sys_test
go
 
PRINT  ''
go
 
 
PRINT  'Multi-statement table-valued function with name "sys_" generates error 1706...'
go
 
CREATE FUNCTION sys_tmp
       ()
RETURNS       @t     TABLE
       (c     INT)
AS
BEGIN
 
       INSERT INTO @t       VALUES (1)
 
       RETURN
 
END
go
 
DROP   FUNCTION sys_test
go
 
PRINT  ''
go
 
/*
----------------------------------------------------------------------------------------------------
*/
 
And here€™s the output from running the test script in Query Analyser on our server:
Microsoft SQL Server  2000 - 8.00.2039 (Intel X86)
       May  3 2005 23:18:38
       Copyright (c) 1988-2003 Microsoft Corporation
       Standard Edition on Windows NT 5.0 (Build 2195: Service Pack 4)
 
Scalar function with name "sys_" creates ok...
 
In-line table-valued function with name "sys_" creates ok...
 
Multi-statement table-valued function with name "sys_" generates error 1706...
Server: Msg 1706, Level 16, State 2, Procedure sys_tmp, Line 11
System table 'sys_tmp' was not created, because ad hoc updates to system catalogs are not enabled.
Server: Msg 3701, Level 11, State 5, Line 2
Cannot drop the function 'sys_test', because it does not exist in the system catalog.

View Replies !
How To Return Multiple Table Values From A Function
Hi,
We Have Been Trying To Convert Some Pf The Procs Into Functions Of Late,but There Is A Problem :-we Have Been Unable To Return More Than 1 Table Value From A Function.

Create Function F_clusters()
Returns @ki Table(names Nvarchar(200),total Int),
As
Begin
Insert @ki
Select Names,count(distinct Chremail) As From Customer
Where Chremail Is Not Null
Return
End

This Works Fine :-
And Gives The Reqd. Results.

But,

If I Am Using The Same Function To Return Two Tables Then It Doesn't Work,could You Pls Chk.



Create Function F_clusters()
Returns @ki Table(names Nvarchar(200),total Int),@k2 Table(names Nvarchar(200),total Int)
As
Begin
Declare @cnt Int
Set @cnt = 1
While @cnt <= 2
If @cnt =1
Begin
Insert @ki
Select Names,count(distinct Chremail) As From Customer
Where Chremail Is Not Null
Set @cnt = @cnt + 1
End
If @cnt =2
Begin
Insert @k2
Select @naamre,count(distinct(a.intcustomerid)) As Pura_ginti From Trcustomerpreference03july A Inner Join Cleancustomer B
On A.intcustomerid = B.intcustomerid
Where Chremail <> ' ' And Chremail Is Not Null
And Intpreferenceid In (6,7,2,3,12,10)
Set @cnt2 = @cnt2 + 1
End
End
Return
End


Can We Return Two Tables Or Is It Not Possible ?
Pls Chk Into This And Tell Me.

Thanks.

View Replies !
Sp_columns In SQL2K5 Gives No Rows For Function That Return Table
Some automated tools use sp_columns to find out the columns for a table, view or UDF that returns table.

In SQL Server 2000 it gives columns back but in SQL Server 2005 it does not, compat level set at 80 and 90.

Does anyone have an idea what id going on here?

Repro script below. I expect the script to return information about the two columns in the table defined in fnTestColumnsFromFunctions().

if exists (select 1
  from sysobjects
  where id = object_id('dbo.fnTestColumnsFromFunctions')
  and type in ('IF', 'FN', 'TF'))
drop function dbo.fnTestColumnsFromFunctions;
go

create function dbo.fnTestColumnsFromFunctions()
returns @TestTable table
(
  ttID int,
  ttName varchar(50)
)
as
begin
   return;
end
go

declare @dbname sysname;
declare @n int;
set @dbname = db_name();
exec @n = dbo.sp_columns
  @table_name = 'fnTestColumnsFromFunctions',
  @table_owner = 'dbo',
  @table_qualifier = @dbname,
  @column_name = null,
  @ODBCVer = 2;

if exists (select 1
  from sysobjects
  where id = object_id('dbo.fnTestColumnsFromFunctions')
  and type in ('IF', 'FN', 'TF'))
drop function dbo.fnTestColumnsFromFunctions;
go

View Replies !
Passing Table Names To Table Valued Functions
Hello,
It is possible to write stored procedures which take table names as parameters; is it also possible to do this with table valued functions?

For example, a simple stored procedure is this:

CREATE PROCEDURE SelectTop(@tableName sysname)
AS
BEGIN

Execute('Select top 10 * from ' + @tableName + ';')

END

I want to be able to do the analogous thing with a table valued function (so that I can query the result set, without having to create a temp table). How should I do this (i.e., pass a tablename as an argument to a table valued function)?

View Replies !

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