I have a function that will return all items in all firms.Table names should be parametric.But I could not create a view from that function.Because I can not return a table.The returned value is a string. Please help.Thanks.
GO
IF OBJECT_ID(N'dbo.ufnGetContactInformation', N'TF') IS NOT NULL
DROP FUNCTION dbo.ufnGetContactInformation;
GO
CREATE FUNCTION dbo.ufnGetContactInformation()
RETURNS @retContactInformation TABLE
(
-- Columns returned by the function
firm nvarchar(50) NULL
)
AS
BEGIN
DECLARE @referans AS INT, @NRP AS INT
DECLARE @TABLE AS NVARCHAR(MAX)
SET @TABLE = ''
DECLARE YourCursorNameHere CURSOR READ_ONLY
FOR
select c1.NR, C2.NR
from L_caPIFIRM c1 WITH(nolock)
INNER JOIN L_CAPIPERIOD C2 WITH(nolock) ON C1.NR=C2.FIRMNR
OPEN YourCursorNameHere
FETCH NEXT FROM YourCursorNameHere INTO @referans, @NRP
WHILE @@FETCH_STATUS = 0
BEGIN
IF @TABLE = ''
SET @TABLE= 'SELECT FIRM=' + str(@referans) +', CODE FROM LG_' + SUBSTRING(('00'+ LTRIM(STR(@referans))),LEN(('00'+ LTRIM(STR(@referans))))-2,3)+ '_ITEMS'
ELSE
SET @TABLE= @TABLE + ' UNION SELECT FIRM=' + str(@referans) +', CODE FROM LG_' + SUBSTRING(('00'+ LTRIM(STR(@referans))),LEN(('00'+ LTRIM(STR(@referans))))-2,3)+ '_ITEMS'
FETCH NEXT FROM YourCursorNameHERE INTO @referans,@NRP
END
-- EXEC( @TABLE)
CLOSE YourCursorNameHere
DEALLOCATE YourCursorNameHere
--BEGIN
-- INSERT INTO select
-- END
RETURN;
END;
GO
Try to use
dynamic
sql
.I didnt check it but maybe this is the way to do it...instead of cursor try while loop