September 8, 2008 at 4:32 am
Dear Experts,
I need to write the following Funtion to output the TimeStr from a TimeCard table as follows:
----------------------------------------------------
CREATE FUNCTION _fGetTimeStr (@ICard int, @DayFile char(8))
RETURNS varchar(100)
AS
BEGIN
declare @tHHMI char(5) -- In format of hh:mi eg. 07:30 or 13:45
declare @result varchar(100) -- Expect output result '07:30,13:45'
SET @tHHMI = ''
SET @result = '--'
-- However the @DayFile is a variable in format: _Xyymmdd eg. _X080901 (sep 1 2008)
DECLARE fil CURSOR FOR
SELECT Xtime FROM _X080901
WHERE ICard = @ICard
ORDER by Xtime
-- Alright when writing the exact table name,
-- but get error when _X080901 is replaced by @DayFile
OPEN fil
FETCH NEXT FROM fil INTO @tHHMI
WHILE @@fetch_status = 0
BEGIN
IF @result = '--'
BEGIN
SET @result = @tHHMI
END
ELSE
BEGIN
SET @result = @result +','+ @tHHMI
END
FETCH NEXT FROM fil INTO @tHHMI
END
CLOSE fil
DEALLOCATE fil
return @result
END
---------------------------------------------
Can any expert suggest me how to do ?
Is there any alternate way to achieve my requirement ?
Thanks a lot for your help !
Regards,
Edward
September 8, 2008 at 8:16 am
The only way to have a variable table name would be to use dynamic SQL. You can't use dynamic SQL in a function.
Can you use a proc instead of a function and have the return value changed to an output parameter?
Alternately, you might be able to create a view that selects the required data from all of the tables, and have the function select from the view. If you regularly add tables (which is a really, really bad idea), you could set up a job to alter the view as needed.
A better idea is to change the table structure so that the date is a column instead of part of the table name. That will prevent all kinds of problems.
- Gus "GSquared", RSVP, OODA, MAP, NMVP, FAQ, SAT, SQL, DNA, RNA, UOI, IOU, AM, PM, AD, BC, BCE, USA, UN, CF, ROFL, LOL, ETC
Property of The Thread
"Nobody knows the age of the human race, but everyone agrees it's old enough to know better." - Anon
September 8, 2008 at 8:39 pm
Hi Lawerance,
Thank you for your suggestions.
I will try to implement by using the stored procedure.
Regards,
Edward
Viewing 3 posts - 1 through 2 (of 2 total)
You must be logged in to reply to this topic. Login to reply