Using A Cursor As A Function Parameter
I've created a function that converts the rows of a column into a delimited string using a passed cursor and delimiter character. In the past I did this in Oracle and called it as shown in the following example:
SELECT Table1.ID, Table1.FirstName, Table1.LastName, fnDelimitRows(CURSOR(SELECT Table2.CourseName FROM Table2 WHERE Table2.StudentID = Table1.ID), ',') AS AssignedCourses FROM Table1
23 John Smith CS101,MT200,BIO100
43 Julio Johnson CS200,ENG100,MT300
How would I pass a cursor into a function in SS like I did above in Oracle?
Thanks!
View Complete Forum Thread with Replies
Related Forum Messages:
Using A Cursor In A Function
I'm creating a user-defined functtion, with a cursor in it.... I really do not understand the errors that I am getting when I try to run my query : Server: Msg 444, Level 16, State 1, Procedure BusStatus_chk, Line 48 Select statements included within a function cannot return data to a client. Server: Msg 444, Level 16, State 1, Procedure BusStatus_chk, Line 66 Select statements included within a function cannot return data to a client. Server: Msg 444, Level 16, State 1, Procedure BusStatus_chk, Line 69 Select statements included within a function cannot return data to a client. The Create procedure statement is as follows: CREATE FUNCTION DBO.BusStatus_chk( @busreg as varchar(10), @wday as tinyint, @stime as smalldatetime, @endtime as smalldatetime ) RETURNS int AS BEGIN DECLARE @totaltime smallint DECLARE @cnt int DECLARE @thisDur smallint Set @cnt = (Select Count(*) from Bus_Status where Bus_Reg = @busreg AND week_day = @wday) IF @cnt > 0 BEGIN Select @thisDur = DATEDIFF(mi, @stime, @endtime); Select @totaltime = SUM(DATEDIFF(mi, Start_time, end_time)) FROM Bus_Status WHERE Bus_Reg=@busreg AND week_day=@wday END; IF @totaltime !> 0 BEGIN Select @totaltime=0; END; IF @thisDur !> 0 BEGIN Select @thisDur = 0 END; Select @totaltime = @totaltime + @thisDur IF @totaltime > 600 BEGIN RETURN 0 END; DECLARE bustimes_cur CURSOR FOR SELECT * FROM Bus_Status WHERE Bus_Reg=@busreg AND week_day=@wday AND @stime BETWEEN start_time and end_time OPEN bustimes_cur FETCH FIRST FROM bustimes_cur WHILE @@FETCH_STATUS = 0 BEGIN FETCH NEXT FROM bustimes_cur END Select @@CURSOR_ROWS IF @@CURSOR_ROWS > 0 BEGIN RETURN 0 END; CLOSE bustimes_cur DEALLOCATE bustimes_cur DECLARE busEndtimes_cur CURSOR FOR SELECT * FROM Bus_Status WHERE Bus_Reg=@busreg AND week_day=@wday AND end_time BETWEEN @stime and @endtime OPEN busEndtimes_cur FETCH FIRST FROM busEndtimes_cur WHILE @@FETCH_STATUS = 0 BEGIN FETCH NEXT FROM busEndtimes_cur END; IF @@CURSOR_ROWS > 0 BEGIN RETURN 0 END; CLOSE busEndtimes_cur DEALLOCATE busEndtimes_cur RETURN 1 END --END OF FUNCTION busStatus_chk :confused: :confused: PLEASE HELP!!!
View Replies !
Split Function With Cursor
Hi, I am trying to write a stored procedure that takes a comma separated letter. I have a split function that returns the splitted letters. I have select some values from the tables in the database where the title starts with each splitted letter. I thought I should use cursor that contains each letter and in the while loop i put my select statement with the conditions. Is this the correct way. Or are there any ideas for this? thanks, Regards, shakthi
View Replies !
Function To Call Function By Name Given As Parameter
I want to write function to call another function which name isparameter to first function. Other parameters should be passed tocalled function.If I call it function('f1',10) it should call f1(10). If I call itfunction('f2',5) it should call f2(5).So far i tried something likeCREATE FUNCTION [dbo].[func] (@f varchar(50),@m money)RETURNS varchar(50) ASBEGINreturn(select 'dbo.'+@f+'('+convert(varchar(50),@m)+')')ENDWhen I call it select dbo.formuła('f_test',1000) it returns'select f_test(1000)', but not value of f_test(1000).What's wrong?Mariusz
View Replies !
Using Cursor As OUT Parameter In Stored Procedure
Hi guys, I have a serious problem. I need to use my cursor as an out parameter, but the problem is, HOW CAN I CLOSE THE CURSOR??????If I dont close the cursor, my server is getting really slow because of the open cursors, cause I have more than 100 stored procedures, which have a cursor as an out-parameter.Here's one of my stored procedures : create or replace PACKAGE pkgResIS TYPE resType IS REF CURSOR RETURN res%ROWTYPE;END pkgRes; create or replace procedure res_sel_val(p_id in number,cs out pkgRes.resType)asBEGIN open cs for select * from res where res_id = p_id; --close cs;EXCEPTION when others then raise_application_error(-20970, 'record kan niet geselecteerd worden');END res_sel_val; How can I close my cursor? If I write the "close cursor" (which is in red at the code above), it returns an empty cursor, which is not my intention.Please help me with thisThanks in advance Morph 'n Nike
View Replies !
Parameter In Declare Cursor Statement
I have to specifiy the database name which is supplied from the user (@fixdb). I want to do something like the following 'code' Declare SysCursor cursor for + 'select Name, ID from ' + @fixdb +'.dbo.sysobjects where xtype = "u"' but I can't seem to come up with the right statement. Any help greatly appreciated. Thanks, Judith
View Replies !
Passing A Parameter To A USE Command Within A Cursor
Hi everyone I am trying to pass a parameter to a USE command within the body of a cursor. I keep getting an error. Here is my code. Code Snippet DECLARE @SQLText AS NVARCHAR(4000) Declare @SQLText2 as NVARCHAR (2000) DECLARE Cursor_Trial CURSOR FOR SELECT name FROM sys.sysdatabases order by name Declare @name as varchar(255) Open Cursor_Trial FETCH NEXT FROM Cursor_Trial INTO @name WHILE @@FETCH_STATUS = 0 BEGIN Use @name --------This is where I'm getting the error Set @SQLText2 = @name select @SQLText2, * from sys.database_principals where type_desc='DATABASE_ROLE' and name = 'xxxxx' FETCH NEXT FROM Cursor_Trial INTO @name END CLOSE Cursor_Trial DEALLOCATE Cursor_Trial As you can see I am trying to pass the next database name into the body of the cursor so that the query will pull the role information only for the current database in the loop. Any thoughts or tips? Is there a better way to accomplish what I'm trying to do here?
View Replies !
Stored Procedure With CURSOR OUTPUT Parameter, Using JDBC And A Callable Statement
My server is MS Sql Server 2005. I'm using com.microsoft.sqlserver.jdbc.SQLServerDriver as the driver class. I've established a connection to the database. I'm trying to invoke a stored procedure using JDBC and a callable statement. The stored procedure has a parameter @CurOut CURSOR VARYING OUTPUT. How do I setup the callable statement so the output parameter is accepted by the driver? I'm not really trying to pass a cursor up to the database Server but I'm wanting a cursor back from the stored procedure that is other than the result set or other value the stored procedure returns. First problem: What java.sql.Types (or SQL Server specific) value do I specify for the out parameter I'm registering on the CallableStatement? Second problem: What do I set the value of the parameter to? The code looks like: CallableStatement cstmt = myConnection.prepareCall(sQuery); cstmt.registerOutParameter(1, Types.OTHER); // What is the right type? cstmt.setNull(1, Types.OTHER); // What is the right type? if (cstmt.execute()) { ResultSet rs = cstmt.getResultSet(); } Execution results in a NullPointerException from the driver. What am I doing wrong? Thanks for your assistance. Jon Weaver
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 !
How Can I Pass A String Parameter More Than 4000 Characters Into Execute() And Return Result For FETCH And Cursor?
Dear All I have no idea to write a store procedure or only query to pass a string parameter more than 4000 characters into execute() and return result for FETCH and Cursor. Here is my query sample for yours to understand. SET NOCOUNT ON DECLARE @ITEMCODE int, @ITEMNAME nvarchar(50), @message varchar(80), @qstring varchar(8000) Set @qstring = 'select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm union select itemcode from oitm' PRINT '-------- ITEM Products Report --------' DECLARE ITEM_cursor CURSOR FOR execute (@qstring) OPEN ITEM_cursor FETCH NEXT FROM ITEM_cursor INTO @ITEMCODE WHILE @@FETCH_STATUS = 0 BEGIN PRINT ' ' SELECT @message = '----- Products From ITEM: ' + @ITEMNAME PRINT @message -- Get the next ITEM. FETCH NEXT FROM ITEM_cursor INTO @ITEMcode END CLOSE ITEM_cursor DEALLOCATE ITEM_cursor Why i use @qstring? It is because the query will be changed by different critiera. Regards Edmund
View Replies !
Function Parameter
I am writing a function which will take two parameters. One the fieldto be returned from a table and second parameter is the ID of therecord to be returned.Problem is it's not returning the value of the field specified in theparameter but instead returns the parameter itself. Is there afunction that will get the parameter to be evaluted first?ALTER FUNCTION [dbo].[getScholarYearData](-- Add the parameters for the function here@FieldName varchar(50), @ScholarID int)RETURNS varchar(255)ASBEGIN-- Declare the return variable hereDECLARE @ResultVar varchar(255)-- Add the T-SQL statements to compute the return value hereSELECT @ResultVar=EXECUTE(@FieldName)FROM dbo.qmaxScholarYearID INNER JOINdbo.tblScholarYears ONdbo.qmaxScholarYearID.ScholarID = dbo.tblScholarYears.ScholarID ANDdbo.qmaxScholarYearID.MaxOfScholarYearID =dbo.tblScholarYears.ScholarYearID-- Return the result of the functionRETURN @ResultVarEND
View Replies !
Parameter In Function
Hi, this has started from me wanting to write a report that allowed the user to choose from a drop down list of how many months they want the report to cover. IE i want the report for the last 3 months, or 5 months or ... To do this i created a report with a value list parameter (values are negative integers to give the necessary start date for the reported rows) and had that parameter in the where clause, along the lines of ... select *blah* from *blah* where ( *myfield* > dateadd (mm, @MonthParam, GetDate()) i get a sql error (ie an error from the database not reporting services) saying that the variable hasnt been declared. I have worked around the problem in this instance but is there a 'feature' in RS that means report parameters cannot take part in functions? TIA
View Replies !
How Specify The Variable As Parameter For A Function
I could successfully modify the package level variable using a script component (Control Flow Level) and execute the data flow task after this script component. The OLE DB Command has one parameter for which I'm using one of the user variable. Here's the SQL statement. SELECT Year_Key, Year_Name, Year_Short_Name, Year_Number, Year_Start_Date, Year_End_Date FROM d_Time_School_Year WHERE (Year_Key = ?) This works fine. But I want to pass the year_key to a function which accepts a parameter. The SQL should be like this SELECT Year_Key, Year_Name, Year_Short_Name, Year_Number, Year_Start_Date, Year_End_Date FROM fn_TimeDimension (?) But SSIS doesn't like this. When I click on parameters command button I get and error like this "Parameters cannot be extracted from the SQL command. The provider might not help......... Syntax error, Permission Violation, or the non-specific error(Microsoft SQL native Client)" Any clue how to utilize the variables in a SQL which gets data from a function instead of a table? Thanks Jemini Joseph
View Replies !
Can't Use Parameter With DateAdd Function??
Hi, I encountered a strange error today. I have an Integer parameter "hours" that I am trying to use in my SQL Query. DATEADD(hh, @hours, @startTime) It works if I have it set such as DATEADD(hh, 8, @startTime), but I need that parameter there for what I need. I get this error: Error Source: System.Data Error Message: Failed to convert parameter value from Decimal to DateTime. I tried a variety of CInt and other conversion functions to no avail. Any ideas?
View Replies !
Multi-value Parameter And Function
I have a report with the following dataset query: Code Snippet SELECT ..., dbo.getActivitySinceBeginningYear(..., @countryId ,...) AS HoursYear FROM .... WHERE cast(detail.COUNTRY_ID as nvarchar(max)) IN (@countryId) AND ... GROUP BY ... countryId is defined as a String multi-valued parameter. The getActivitySinceBeginningYear is defined as follows: Code Snippet ALTER FUNCTION dbo.getActivitySinceBeginningYear ( ... @countryId ntext, ... ) RETURNS decimal(18,5) AS BEGIN declare @return decimal(18,5) set @return = 0.0 SELECT @return = SUM(detail.HOURS_WORKED) FROM ... inner join charlist_to_table(@countryId, Default) f on detail.COUNTRY_ID = f.str WHERE ... RETURN @return END This function works as expected if I transmit one ID or several. The report works fine if I check only one ID. If I check several IDs, the report displays this error: Procedure or function dbo.getActivitySinceBeginningYear has too many arguments specified. Why??? My second problem is with the Where clause: Code Snippet WHERE cast(detail.COUNTRY_ID as nvarchar(max)) IN (@countryId) If I do: Code SnippetWHERE detail.COUNTRY_ID IN (@countryId) I have the following error: Conversion failed when converting the nvarchar value '3,5' to data type int. (I transmitted 3 and 5 for countryId) That's why I tried to use a cast, but the data returned by the query is wrong when I transmit several value. ??
View Replies !
Function Help: Parameter Query
What SQL Function Criteria string replaces [forms]![myForm].[myField]? I have a function that I want to pass criteria to from a drop down list. I tried using the same Access string in the Function but it does not work.
View Replies !
Passing Parameter In Function
I have to pass 3parameters in function, @begindate,@enddate and @group_type.. but in @group_type should be - state,zipcode and country from salestable inview :vwstzipcont create view vwstzipcont as select distinct s2.stype,s3.itemnmbr,s2.docdate,s3.state,s3.zipcode,s3.country from Salestable s3 left outer join (select distinct stype,docdate from salesdisttable) s2 on s2.stype = s3.stype where s2.soptype = 2 go create function mystzipcont ( @begindate datetime, @enddate datetime, @group_type char(70)) RETURNS TABLE AS RETURN (Select distinct t.docdate,t.itemnmbr,t.index,t.group_type from ( select distinct vs.docdate,vs.itemnmbr, p.index From Pubs P inner join vwstzipcont vs on vs.index = p.index Where (vs.docdate between @begindate and @enddate) and @group_type ) as t order by t.itemnmbr,t.docdate end how can i assign @group_type variable or t.group_type? in s3.state,s3.zipcode,s3.country can anyone tell me? what condition should be in where clause for this variable? thanks
View Replies !
Table Name As Function Parameter
I'm trying to write a function that I can run with passing the table name as a parameter. I want to return an integer. The tables wll be differnet types (different colums) but they all have a similar field that i want to get a count of. Someting alng the lines of this: Create FUNCTION [dbo].[fn_GetItemsToPromote] ( @TableName nvarchar(100) ) RETURNS int AS BEGIN Declare @SQL nvarchar(500) return select count(*) from [@TableName]where promote = 1 END It doesnt like the @TableName. Can anyone show me how to do this correctly? Thanks!
View Replies !
How To Pass Parameter In Max Aggregate Function
i have on table temp and it has column name fhID, now that column name and table name comes as parameter in stored procedure from c#. now stored procedure has code somthing like below @column nvarchar(50) @tbname nvarchar(50) -- both are parameter comes from c# decalre @maxid select @maxid=max(@column) from @tbname rather than prints the maximum values of "fhid" it prints column name itself. now i how can i achive actual working of max function using parameter. is there any other way to pass parameter in aggregate function or it is not allowed to pass.??? plz help me, thanks vishal parekh 'fhid' now how can
View Replies !
Function That Take A Table As Input Parameter
hi all i am using VS 2005 with SQL Server 2005 and i faced a problem that need to be solved urgently... i want to make a function that take a table as input parameter which is the output of a stored procedure (Record set)... first i found that to make w table be as input parameter you must create type of that table first but i found that sql server 2005 doesn't have the 'table' as a type... please any help will be appreciated thanks in advance
View Replies !
Pass Table As A Parameter To A Function
Hi Friends,Is it possible to pass a table as a parameter to a funtion.whos function declaration would look some thing like this....ALTER FUNCTION TempFunction (@TempTable TABLE, @nPId INT)my problem is: i have to access a temporary table created in an SP ina functionALTER PROCEDURE MySPBEGIN....DECLARE @TmpTable TABLE(...)....TempFunction(@TmpTable)....ENDThanksArunDhaJ
View Replies !
Passing Table Name As Parameter To Function
Hi all. I'm writing reports in Rep. Services that reads data from Dynamics NAV (Navision). In NAV data are stored by company and this is implemented by using the company name as prefix to the table name. This means that in a NAV database with three companies (lets call these companies A, B and C) we will have three tables with customers. The table names will be A$Customer, B$Customer and C$Customer. Now to my problem: I wan't to write one report where I can choose company. I do not want to use a stored procedure. I want to use a function so I can use the function in select statements and join several functions to build up a report that needs data from several tables. Is there some way to pass the table name or a part of the table name to a function that returns the content of the actual table? I know I can pass parameters that I can use in the where clause, but is it possible to do it with the table name. Or is there any other way to solve this. All ideas are welcome. Thanks.
View Replies !
Function That Take A Table As Input Parameter
i want to make a function that will take a table as input parameter. this table will be the output of a stored procedure. while i were writing the function i have an error and when i read about it i found that i can not send a table as input parameter to a function till i create a new TYPE of this table with its columns and data types as UDT but i found that sql server 2005 does not support the type 'table'... my question now is it possible technically to make this function? is it possible to write something like that : SELECT dbo.MyFunction(exec dbo.MystoredProc) and in my function i am using CLR-Integration as this : create function MyFunction ( @TempTable table ( ContractID int, ContractNumber nvarchar(20), Name_En nvarchar(80), Name_Ar nvarchar(80), ContractAmount money, CurrencyID nchar(3), DateStart smalldatetime, DateEnd smalldatetime, Currency_En nvarchar(30), Currency_Ar nvarchar(30) ) ) returns table( ContractNumber nvarchar(20), Name_En nvarchar(80), Name_Ar nvarchar(80), ContractAmount decimal, Currency_En nvarchar(30), Currency_Ar nvarchar(30), [Year] int, [Month] int, DomesticAmount decimal ) as external name [AssemblyName].[PathOfTheFunctionInTheAssembly].[FunctionNameInAssembly] please help me in this code as i need it urgently... thanks in advance, best regards, Moustafa
View Replies !
Multi Parameter Aggregate CLR-function?
In the provided CLR-function sample there is only one parameter from the SQL statement to the function. I can't find any info about how to pass more then one parameter. Is this possible somehow? like: Code Snippet Select ShopCode,PickAValue(OrderDate,Article) as BestArticle from T_Sales Group by ShopCode hans
View Replies !
Input Parameter To Function In SQL Query
I am trying to use a Execute SQL task in which I call a query and get back a scalar value. I THINK I have it set up correctly, yet I am getting a very unhelpful error message of: Error: 0xC002F210 at Determine Previous Trade Date, Execute SQL Task: Executing the query "SELECT[Supporting].[dbo].[fGetOffsetTradeDate](?, -1) AS [PreviousTradeDate]" failed with the following error: "Syntax error, permission violation, or other nonspecific error". Possible failure reasons: Problems with the query, "ResultSet" property not set correctly, parameters not set correctly, or connection not established correctly. The Parameter Mapping has a single INPUT entry of data type DATE mapped to parameter 0. The Result Set property (in General) is set to Single Row and there is a single entry in the Result Set config which maps [PreviousTradeDate] to a variable. Odd thing is, if I replace the ? in the query with a date (say '03/24/2006') everything works fine. This would indicate that my query syntax is fine.
View Replies !
Is It Possible To Set The Query Parameter By Giving A Function Name
I am trying to do a query similar to this: SELECT * FROM TRANSACCTION_HISTORY WHERE TXN_DATE=@RepDate For the query parameter @RepDate, I would like to pass a function to it. The function is a calculation of date based on today's date (e.g. Today() function to be simple). So that users don't have to type in the date every time. Now the question is: is it really possible to do that in RS? Because I am getting a type conversion error, when I put Today() in the Define Query Parameters disalog box. Thanks for helping!
View Replies !
Passing A Suquery To A Function As A Parameter
How would one pass a subquery to a function as a parameter? I have a function, f_Split that returns a table and has two parameters @List varchar(max) and @Delim char(1). I'd like to use it to normalize rows in a table and return the results for use in a report. I tried the following: SELECT * FROM dbo.f_Split((SELECT Code FROM Codes WHERE ID = 10), '|') I'm getting a syntax error for the subquery. Could anyone show me the proper way to pass a subquery to a function, even if the function is different from what I have defined here. Thanks, DD
View Replies !
Function With A Parameter Of Type Object.
Hello, I would like to create a function that accepts a value of any type as parameter. I mean, it could receive a value of type int, datetime, char,... In .net, I would use the type "object". Is there an equivalent for SQL server function ? Regards, mathmax
View Replies !
Using A Function To Pass A Parameter To A Stored Procedure
In the snippet below, ExecuteSqlString is a stored procedure that accepts one parameter. SelectChangeDropdownRowsource is a function in my code behind page that generates the string I want to pass. I can't seem to find the correct syntax to get it to work. The way it is show below, the error comes back about incorrect syntax near ')' . Is this doable? <asp:SqlDataSource ID="ChangeInfo" runat="server" ConnectionString="<%$ ConnectionStrings:xxx %>" DataSourceMode="DataReader" ProviderName="<%$ ConnectionStrings:xxx %>" SelectCommandType=StoredProcedure SelectCommand="ExecuteSqlString"> <selectparameters> <asp:parameter name="sqlString" Type=String DefaultValue=SelectChangeDropdownRowsource()/> </selectparameters> </asp:SqlDataSource>
View Replies !
Sending Column Name As A Parameter To Aggregate Function
How can do this. Because my stored function contains same clause except colums name.So I want to use column name as a parameter but how can send column name and use it like Sum(parameter) function . my procedure like this: ALTER PROCEDURE [dbo].[ORNEK10] @YIL VARCHAR(4), @TEKLIF_TURU VARCHAR(255) AS BEGIN DECLARE @N1 FLOAT DECLARE @N2 FLOAT SET @N1 = ( SELECT DEGERI FROM PARAMETRE WHERE PARAMETRE_ADI='N1') SET @N2 = ( SELECT DEGERI FROM PARAMETRE WHERE PARAMETRE_ADI='N2') SET NOCOUNT ON; --I want to avoid using if statements for Sum() function IF(@TEKLIF_TURU='BASKAN_TEKLIF') SELECT TOP (100) PERCENT KOD1, KOD2, KOD3, KOD4, dbo.ORNEK10AD(KOD1, KOD2, KOD3, KOD4) AS ACIKLAMA, SUM(BASKAN_TEKLIF) AS YILI, ((100+@N1)*SUM(BASKAN_TEKLIF))/100 AS YIL1, ((100+@N1)*(100+@N2)*SUM(BASKAN_TEKLIF))/10000 AS YIL2 FROM GELIR AS G WHERE YIL = @YIL GROUP BY KOD1, KOD2, KOD3, KOD4 WITH ROLLUP ORDER BY KOD1, KOD2, KOD3, KOD4 IF(@TEKLIF_TURU='ENCUMEN_TEKLIF') SELECT TOP (100) PERCENT KOD1, KOD2, KOD3, KOD4, dbo.ORNEK10AD(KOD1, KOD2, KOD3, KOD4) AS ACIKLAMA, SUM(ENCUMEN_TEKLIF) AS YILI, ((100+@N1)*SUM(ENCUMEN_TEKLIF))/100 AS YIL1, ((100+@N1)*(100+@N2)*SUM(ENCUMEN_TEKLIF))/10000 AS YIL2 FROM GELIR AS G WHERE YIL = @YIL GROUP BY KOD1, KOD2, KOD3, KOD4 WITH ROLLUP ORDER BY KOD1, KOD2, KOD3, KOD4 IF(@TEKLIF_TURU='MECLIS_TEKLIF') SELECT TOP (100) PERCENT KOD1, KOD2, KOD3, KOD4, dbo.ORNEK10AD(KOD1, KOD2, KOD3, KOD4) AS ACIKLAMA, SUM(MECLIS_TEKLIF) AS YILI, ((100+@N1)*SUM(MECLIS_TEKLIF))/100 AS YIL1, ((100+@N1)*(100+@N2)*SUM(MECLIS_TEKLIF))/10000 AS YIL2 FROM GELIR AS G WHERE YIL = @YIL GROUP BY KOD1, KOD2, KOD3, KOD4 WITH ROLLUP ORDER BY KOD1, KOD2, KOD3, KOD4 END
View Replies !
Coma Separated String Value As Function Parameter
Hi Let€™s say I have employees table that contains id column for the supervisor of the employee. I need to create a function that gets coma separated string value of the supervisors€™ ids, And return the ids of employees that the ENTIRE listed supervisors are there supervisor. (some thing like €œSelect id from employees where supervisor=val_1 and supervisor=val_2 and €¦ and supervisor=val_N) Is there a way to create this function without using sp_exec? I€™ve created a function that splits the coma separated value to INT table. (For use in a function that do something like: €œSelect id from employees where supervisor in (select val from dbo.SplitToInt(coma_separated_value)) ) Thanks , Z
View Replies !
How To Write A Function With Integer Parameter Accepting Null
I've got a function which inserts into a database, and has arguments for each item being inserted A couple of the items are integer datatypes (in SQL), but they will accept nulls When I add my parameters, it asks to explicitly use the SQL datatype (which is integer):.Add("@myParam", SqlDbType.Int).Value = myParam In the header of the function, I assumed I could make the argument optional - Optional ByVal myParam as Integer=System.DBNull.Value However, when the function runs, I always get an error:System.InvalidCastException was unhandled by user code Message="Conversion from type 'DBNull' to type 'Integer' is not valid." I make them all Optional (which won't happen, but various arguments may be, at different timesand I get this error, with the last item (which is on a separate line), in red:Constant expression is required. How can I get around this?
View Replies !
Invalid Length Parameter Passed To The SUBSTRING Function
SELECT C.Description, SUBSTRING ( (CONVERT (VARCHAR (255), D.CurrentXmlValue)), --expression (CHARINDEX ('>', CONVERT (VARCHAR (255), D.CurrentXmlValue)) + 1), --start ( (LEN (CONVERT (VARCHAR (255), D.CurrentXmlValue))) - (CHARINDEX ('>', CONVERT (VARCHAR (255), D.CurrentXmlValue))*2) - 1 )--length ) AS Version FROM : : WHERE : : This does not work while : : --SUBSTRING ( (CONVERT (VARCHAR (255), D.CurrentXmlValue)) as expression, --expression (CHARINDEX ('>', CONVERT (VARCHAR (255), D.CurrentXmlValue)) + 1) as start, --start ( (LEN (CONVERT (VARCHAR (255), D.CurrentXmlValue))) - (CHARINDEX ('>', CONVERT (VARCHAR (255), D.CurrentXmlValue))*2) - 1 ) as length --length --) AS Version : : works!! I get Msg 536, Level 16, State 5, Line 2 Invalid length parameter passed to the SUBSTRING function. Error. Any idea why i am getting this?? I am trying to get rid of xml tags in the column. 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 !
Invalid Length Parameter Passed To The SUBSTRING Function.
Hi, I was trying to execute the following query. select substring(ISNULL(CAST(FullAdress AS NVARCHAR(MAX)),''),1,charindex(',',ISNULL(CAST(FullAdress AS NVARCHAR(MAX)),''))-1) from tbl_lrf_company_details_with_codes but i am getting the error as "Invalid length parameter passed to the SUBSTRING function." Please advice Thanks In advance
View Replies !
Procedure Or Function 'selectFromView' Expects Parameter '@Year', Which Was Not Supplied. ???
hay all, i'm trying to pass parameters to a stored procedure ..and i keep getting this error "Procedure or function 'selectFromView' expects parameter '@Year', which was not supplied." this is the procedure implementation : ALTER PROCEDURE dbo.selectFromView @Year as varchar(10), @Country as varchar(10), @Family as varchar(10), @Manu as varchar(10), @Status as varchar(10), @Type as varchar(10), @Operator as varchar(10) AS SELECT * FROM ViewofAll WHERE ProductionYear = @Year and CountryName = @Country and Family = @Family and Manufacturer = @Manu and Status = @Status and Type = @Type and OperatorName = @Operator RETURN and below how i call the procedure : Dim connection As SqlConnection connection = New SqlConnection() connection.ConnectionString = "Data Source=BLACKIRIS3SQLEXPRESS;Initial Catalog=Aircrafts;Integrated Security=True" connection.Open() Dim command As SqlCommand command = New SqlCommand("selectFromView", connection) command.CommandType = CommandType.StoredProcedure command.Parameters.Add(New SqlParameter("@Year", System.Data.SqlDbType.VarChar, 100)).Direction = ParameterDirection.Input command.Parameters.Add(New SqlParameter("@Country", System.Data.SqlDbType.VarChar, 100)).Direction = ParameterDirection.Input command.Parameters.Add(New SqlParameter("@Family", System.Data.SqlDbType.VarChar, 100)).Direction = ParameterDirection.Input command.Parameters.Add(New SqlParameter("@Manu", System.Data.SqlDbType.VarChar, 100)).Direction = ParameterDirection.Input 'Stored prcedure parameters command.Parameters.Add(New SqlParameter("@Status", System.Data.SqlDbType.VarChar, 100)).Direction = ParameterDirection.Input command.Parameters.Add(New SqlParameter("@Type", System.Data.SqlDbType.VarChar, 100)).Direction = ParameterDirection.Input command.Parameters.Add(New SqlParameter("@Operator", System.Data.SqlDbType.VarChar, 100)).Direction = ParameterDirection.Input command.Parameters.Item("@Year").Value = myArray(0) command.Parameters.Item("@Country").Value = myArray(1) command.Parameters.Item("@Family").Value = myArray(2) command.Parameters.Item("@Manu").Value = myArray(3) command.Parameters.Item("@Status").Value = myArray(4) command.Parameters.Item("@Type").Value = myArray(5) command.Parameters.Item("@Operator").Value = myArray(5) DSGrid.SelectCommand = command.CommandText With DSGrid .DataBind() End With i'm not really familiar with stored procedures ...any one can help me plz ? thanx in advance .
View Replies !
Procedure Or Function 'SubscribeToNewsletters' Expects Parameter '@emailAddress', Which Was Not Supplied.
Hi i have been trying to insert some values selected in a checkbox list into the database, however it is giving me the following error "Procedure or Function 'SubscribeToNewsletters' expects parameter '@emailAddress', which was not supplied. "public void Page_Load(object sender, EventArgs e) -- on page load the checkbox list is populated through stored procedure (stream_NewsletterTypes) { try {SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["streamConnectionString"].ConnectionString); SqlCommand command = new SqlCommand("stream_NewsletterTypes", conn); command.CommandType = CommandType.StoredProcedure; command.Connection.Open();SqlDataReader datareader = command.ExecuteReader(); AlertList.DataSource = datareader;AlertList.DataTextField = "newsletterName"; AlertList.DataBind(); command.Connection.Close(); command.Connection.Dispose(); }catch (Exception ex) {throw new Exception("Exception. " + ex.Message); } } protected void Btn_Subscribe_Click(object sender, EventArgs e) when the button is clicked, the values should be sent to the database {SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["streamConnectionString"].ConnectionString); SqlCommand command = new SqlCommand("stream_NewsletterTypes", conn);command.CommandType = CommandType.StoredProcedure;for (int i = 0; i < AlertList.Items.Count; i++) {if (AlertList.Items[i].Selected) { command.Parameters.AddWithValue("firstName", txtFirstName.Text);command.Parameters.AddWithValue("surname", txtSurname.Text); command.Parameters.AddWithValue("emailAddress", txtEmail.Text);command.Parameters.AddWithValue("newsletterID", AlertList.Items[i].Value); } } try { conn.Open(); command.ExecuteNonQuery(); }catch (Exception ex) {throw new Exception("Exception adding account. " + ex.Message); } finally { conn.Close(); } } And my stored procedure;ALTER PROCEDURE [dbo].[SubscribeToNewsletters] @emailAddress VARCHAR(250), @firstName VARCHAR(250), @surname VARCHAR(250), @newsletterID INT,@userID INT OUTPUT AS INSERT INTO ThinkUsers (emailAddress, firstName, surname) VALUES (@emailAddress, @firstName, @surname) Select @userID = @@Identity -- this is the ID created in the TheUserTable -- when you make that first insert, the database -- will generate the next ID value in that table INSERT INTO SubscribedNewsletters (userID, newsletterID) VALUES (@userID, @newsletterID)
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 !
Procedure Or Function 'retrieve_product' Expects Parameter '@productPrice', Which Was Not Supplied.
Hi i am getting this error whenever i try to execute a stored procedure, below is my stored procedure; ALTER PROCEDURE [dbo].[retrieve_product] -- Add the parameters for the stored procedure here @productPrice decimal (10,2), @productInfoURL varchar (255), @categoryName varchar (255),@companyName varchar (255), @subCategoryName varchar (255), @companyWebsiteURL varchar (255) AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. SET NOCOUNT ON; -- Insert statements for procedure here SELECT Categories.categoryName, SubCategories.subCategoryName,Companies.companyName, Products.productPrice, Products.productInfoURL FROM Categories INNER JOIN Products ON Categories.categoryID = Products.categoryID INNER JOIN Companies ON Products.companyID = Companies.companyID INNER JOIN SubCategories ON Categories.categoryID = SubCategories.categoryID AND Products.subcategoryID = SubCategories.subCategoryID END
View Replies !
Procedure Or Function 'syl_EmailQueueInsert' Expects Parameter '@EmailCC', Which Was Not Supplied.
We have a email table in the database (SQL Server 2005). When we try to execute the Insert Stored Proc in the database to add a record and leave the EmailCC and EmailBCC fields blank we are getting the following error: Msg 201, Level 16, State 4, Procedure syl_EmailQueueInsert, Line 0Procedure or Function 'syl_EmailQueueInsert' expects parameter '@EmailCC', which was not supplied. The EmailCC and EmailBCC are set to allow nulls. Shouldn’t the system automatically insert nulls into those colums if no value is supplied??? What am I doing wrong? Newbie
View Replies !
Sql 2005 ... Invalid Length Parameter Passed To The SUBSTRING Function.
Hi, I am new at sql 2000 and 2005, I have created a package in 2005 which I am trying to execute on a daily bases by creating a job. At first because of security issues the job would not execute. Hence, I had to create a credential and a proxy to run the job with sa account. Now it is giving me this error, €œSQLServer Error: 536, Invalid length parameter passed to the SUBSTRING function. €œ Through research I have no clue as what I need to do, or where to look. The package runs without error when I execute the package itself. Any help is greatly appreciated. Thanks, Lori
View Replies !
Error: Invalid Length Parameter Passed To The SUBSTRING Function.
Hi, I am using a simple procedure to pivot results (found in another forum and adapted it). It is done on SQL Server 2005 server with all service packs. Procedure: ************** ALTER Procedure [dbo].[EthnicityPivot] @StDate as Datetime, @EndDate as Datetime as begin DECLARE @Teams varchar(2000) truncate table ForEthnicPivot INSERT INTO ForEthnicPivot SELECT DISTINCT COUNT(ID), Team, Ethnicity FROM dbo._EthnicityByTeamEpisode where Startdate between @StDate and @EndDate GROUP BY Ethnicity, Team SET @Teams = '' --// Get a list of the pivot columns that are important to you. SELECT @Teams = @Teams + '[' + Team + '],' FROM (SELECT Distinct Team FROM ForEthnicPivot) Team --// Remove the trailing comma SET @Teams = LEFT(@Teams, LEN(@Teams)-1) --// Now execute the Select with the PIVOT and dynamically add the list --// of dates for the columns EXEC( 'SELECT * FROM ForEthnicPivot PIVOT (SUM(countID) FOR Team IN (' + @Teams + ')) AS X' ) end ************ I can call the function: exec EthnicityPivot '01/01/2007','09/09/2007' and it works fine in SQL analyzer, but when I want to use it in Visual Studio in a new report I am getting this error message: There is an error in the query. Invalid length parameter passed to the SUBSTRING function. Incorrect syntax near ')'. Anyone had similar error and sorted it? Cheers Polda
View Replies !
Procedure Or Function 'insertProjectDetails' Expects Parameter '@ProjectTitle', Which Was Not Supplied.?
Running [dbo].[insertProjectDetails] ( @ProjectTitle = <DEFAULT>, @ProjectPeriod = <DEFAULT>, @Client = <DEFAULT>, @Position = <DEFAULT>, @ProjectDescription = <DEFAULT>, @Responsiblities = <DEFAULT>, @OtherInformation = <DEFAULT> ). Procedure or Function 'insertProjectDetails' expects parameter '@ProjectTitle', which was not supplied. No rows affected. (0 row(s) returned) @RETURN_VALUE = Finished running [dbo].[insertProjectDetails]. Can any body send solution for this error?
View Replies !
Passing Parameter Query From SQL Function To Access Project Report
I can pass a parameter from an Access Query to an Access Report (MDB) by entering [Select Date] in the Query criteria and by placing an unbound control with a control source =[Select Date] on the report. I can't get this to work from a SQL Function Criteria to an unbound control on the Access Data Project Report. In the Function Criteria, I enter @SelectDate. In the Report control, I enter @SelectDate and it gives me an 'Invalide Column Name' error. Any idea how I can pass a parameter from a SQL Function to an ADP report? THANKS! p.s. I tried searching for other postings on this without any luck.
View Replies !
OLAP Multi Value Parameter Error:Members Belong To Different Hierarchies In The STRTOSET Function
Hi - I am building a reoprt (SSRS, SQL Server 2005) with a multi value parameter that exposes a picklist on the report page - when ALL is selected, or certain combinations of the elements in the picklist are chosen, I get the following error, that a query failed for a dataset because: Members Belong to Different hierarchies in the STRTOSET function. I have built reports with multiple value pick list before, and not encountered tis error. Any ideas? I cannot find a reference to this error anywhere. Thanks Bob
View Replies !
Dynamic Cursor Versus Forward Only Cursor Gives Poor Performance
Hello,I have a test database with table A containing 10,000 rows and a tableB containing 100,000 rows. Rows in B are "children" of rows in A -each row in A has 10 related rows in B (ie. B has a foreign key to A).Using ODBC I am executing the following loop 10,000 times, expressedbelow in pseudo-code:"select * from A order by a_pk option (fast 1)""fetch from A result set""select * from B where where fk_to_a = 'xxx' order by b_pk option(fast 1)""fetch from B result set" repeated 10 timesIn the above psueod-code 'xxx' is the primary key of the current Arow. NOTE: it is not a mistake that we are repeatedly doing the Aquery and retrieving only the first row.When the queries use fast-forward-only cursors this takes about 2.5minutes. When the queries use dynamic cursors this takes about 1 hour.Does anyone know why the dynamic cursor is killing performance?Because of the SQL Server ODBC driver it is not possible to havenested/multiple fast-forward-only cursors, hence I need to exploreother alternatives.I can only assume that a different query plan is getting constructedfor the dynamic cursor case versus the fast forward only cursor, but Ihave no way of finding out what that query plan is.All help appreciated.Kevin
View Replies !
|