Passing parameters to table valued functions and using parameters as column name on select
I am creating a function where I want to pass it parameters and then use those parameters in a select statement. When I do that it selects the variable name as a literal not a column. How do I switch that context.
Query:
ALTER FUNCTION [dbo].[ufn_Banner_Orion_Employee_Comparison_parser_v2]
@BANNER_COLUMN AS VARCHAR(MAX),
@ORION_COLUMN AS VARCHAR(MAX)
RETURNS @Banner_Orion_Employee_Comparison TABLE
LAST_NAME nvarchar(max),
EMPNO int,
BannerColumnName nvarchar(max),
BANNER nvarchar(max),
ORION nvarchar(max)
AS
BEGIN
INSERT INTO @Banner_Orion_Employee_Comparison
(LAST_NAME, BANNER, ORION)
SELECT
a.LAST_NAME, @BANNER_COLUMN, @ORION_COLUMN
FROM OPENQUERY(ORCLPROD_APDORACLE, 'select LAST_NAME, BANNER_RANK, BADGE, EMP_STATUS from XTRACT_VIEW') AS a
inner join IWM_Stage.dbo.ViewPersonnel AS b
on a.BADGE = b.badge
WHERE a.EMP_STATUS = 'A'
and a.BANNER_RANK <> b.[rank]
RETURN;
END;
GO
Output
I execute this:
select * from ufn_Banner_Orion_Employee_Comparison_parser_v2 ('a.BANNER_RANK' , 'b.[rank]')
and get:
Cerecerez NULL
NULL a.BANNER_RANK
b.[rank]
George,
You could go for using a CASE statement as earlier mentioned by Erland. This would look like below: (Downside is that you need to be mentioning all possible values in the CASE)
ALTER FUNCTION [dbo].[ufn_Banner_Orion_Employee_Comparison_parser_v2]
@BANNER_COLUMN AS VARCHAR(MAX),
@ORION_COLUMN AS VARCHAR(MAX)
RETURNS @Banner_Orion_Employee_Comparison TABLE
LAST_NAME nvarchar(max),
EMPNO int,
BannerColumnName nvarchar(max),
BANNER nvarchar(max),
ORION nvarchar(max)
AS
BEGIN
INSERT INTO @Banner_Orion_Employee_Comparison(LAST_NAME, BANNER, ORION)
SELECT
a.LAST_NAME
, CASE @BANNER_COLUMN WHEN 'a.BANNER_RANK' THEN a.BANNER_RANK WHEN 'a.BADGE' THEN a.BADGE END --put values as required
, CASE @ORION_COLUMN WHEN 'b.[rank]' THEN b.[rank] END --put values as required
FROM OPENQUERY(ORCLPROD_APDORACLE, 'select LAST_NAME, BANNER_RANK, BADGE, EMP_STATUS from XTRACT_VIEW') AS a
inner join IWM_Stage.dbo.ViewPersonnel AS b
on a.BADGE = b.badge
WHERE a.EMP_STATUS = 'A'
and a.BANNER_RANK <> b.[rank]
RETURN;
END;
GO
Another method that I would suggest is to get all values from the function, then build a dynamic query to obtain results from it .. Something like:
ALTER FUNCTION [dbo].[ufn_Banner_Orion_Employee_Comparison_parser_v2]()
RETURNS @Banner_Orion_Employee_Comparison TABLE
LAST_NAME nvarchar(max),
EMPNO int,
BannerColumnName nvarchar(max),
BANNER nvarchar(max),
ORION nvarchar(max)
AS
BEGIN
INSERT INTO @Banner_Orion_Employee_Comparison(LAST_NAME, BANNER, ORION)
SELECT
* --Returns all the columns
FROM OPENQUERY(ORCLPROD_APDORACLE, 'select LAST_NAME, BANNER_RANK, BADGE, EMP_STATUS from XTRACT_VIEW') AS a
inner join IWM_Stage.dbo.ViewPersonnel AS b
on a.BADGE = b.badge
WHERE a.EMP_STATUS = 'A'
and a.BANNER_RANK <> b.[rank]
RETURN;
END;
GO
--Execution
DECLARE @BANNER_COLUMN AS VARCHAR(MAX), @ORION_COLUMN AS VARCHAR(MAX),@SQL NVARCHAR(MAX)
SET @BANNER_COLUMN='BANNER_RANK'
SET @ORION_COLUMN='[rank]'
SET @SQL='
select LAST_NAME,'+@BANNER_COLUMN+','+@ORION_COLUMN+' from ufn_Banner_Orion_Employee_Comparison_parser_v2 ()'
PRINT @SQL
EXEC @SQL
You just need to make sure that the column names returned by the function are UNIQUE (Using proper alias names) so that you don't have a problem referring to them from the outside..
Thanks,
Jay
<If the post was helpful mark as 'Helpful' and if the post answered your query, mark as 'Answered'>
Similar Messages
-
In which condition Table valued function should prefer over SP except use in joins?
Hi,
My requirements is:
Entity framework needs to call DB object (TVF or SP), which will provide some data to them and they'll work on it at app level.
DB object would be simple, one result set, it will join 5 tables and get around 30 columns to them. it would be parameterized query so can't use view.
Now my question is what DB object would be best to use, table valued function or store procedure. and why?
I google on it, I find some interesting links (example http://technet.microsoft.com/en-us/library/ms187650(v=sql.105).aspx)
they mentioned conditions to convert SP to TVF but not mentioned the reason, why I should convert?
Both have same cache plans strategy. SP has so many advantages over TVF, but I don't see any technical advantage of TVF over SP except it can be use in joins or so.
so In short my question is, why I can't use SP in all cases, why I would use TVF?, and which Table valued or multi-valued?
would appreciate your time and response.According to a few recent blogs you should be able to use TVP or stored procedure with EF 6.1.2 with ease. In our application we haven't switched yet to 6.1.2 (we're using 6.0.0) and there is no support for stored procedures or functions so we use StoreQuery.
I am wondering if you can share your experience of using EF with SP or TVP (and document the steps).
I am also wondering as how exactly it's working behind the scenes and where the full query is taking place. Say, in our case we may want to add some extra conditions after retrieving a set using, say, SP. Would the final query execute on the client (e.g.
SP executed on the server, result returned and then extra conditions executed on the "client")?
As I said, right now we're using StoreQuery which means that our extra conditions must be case - sensitive as opposed to SQL Server case insensitive. So, if someone already tried that scenario and can tell me how exactly it works, I would appreciate it.
Another question about EF - I defined a property as
[Column(TypeName = "varchar")]
public string PhoneNumber { get; set; } // area code + phone
and in the LINQ query as
var query = db.Accounts.Select(a => new AccountsList
AcctName = a.AcctName,
Contact = a.Contact,
FullName = a.FullName,
AreaCode = a.AreaCode,
Phone = a.Phone,
Hidden = a.Hide,
Hide = a.Hide,
PhoneNumber = a.AreaCode.Trim() + a.Phone.Trim(),
AcctTypeId = a.AcctTypeId
and I see that it's translated into CASE AreaCode IS NULL THEN N'' ELSE RTRIM(LTRIM(areaCode)) END + ...
My question is - why EF does it if there is no mentioning at all in the class as how NULL is supposed to be treated. Is it a bug?
For every expert, there is an equal and opposite expert. - Becker's Law
My blog
My TechNet articles -
Problem with dg4msql and table-valued functions
Have configured dg4msql to connect from my oracle db to ms sql server.
Am able to do simple SELECTs from ms sql tables like:
select * from "sys"."procedures"@dg4msql;
or
select * from "dbo"."SomeTable"@dg4msql;
But am unable to do a SELECT from a table-valued function:
select * from "dbo"."GetData"@dg4msql('param1value');
or
select * from "dbo"."GetData"('param1value')@dg4msql;
In both cases I get:
ORA-00933: SQL command not properly ended
It does not like the parameters portion of the query ("('param1value')")
initdg4msql.ora:
HS_FDS_CONNECT_INFO=[svr1]//mydb
HS_FDS_TRACE_LEVEL=OFF
HS_FDS_PROC_IS_FUNCT=TRUE
HS_FDS_RESULTSET_SUPPORT=TRUE
Have tried the other set of params:
HS_FDS_PROC_IS_FUNCT=FALSE
HS_FDS_RESULTSET_SUPPORT=TRUE
Same story. After changing the init*** file have bounced both Listeners (DB and Gateway), reconnected, and re-run the query.
Have I missed something?
Any help is greatly appreciated!Sorry, but for me it looks you did not get the problem.
Oracle® Database Gateway for SQL Server User's Guide,:
11g Release 2 (11.2)
Part Number E12069-02
*2 SQL Server Gateway Features and Restriction*
Result Sets and Stored Procedures
The Oracle Database Gateway for SQL Server provides support for stored procedures which return result sets.
By default, all stored procedures and functions do not return a result set to the user. To enable result sets, set the HS_FDS_RESULTSET_SUPPORT parameter value to TRUE.
PL/SQL Program Fetching from Result Sets in Sequential Mode
-- Execute procedure
out_arg := null;
refcurproc@MSQL('Hello World', out_arg, rc1);
Somewhere in this forum I've seen a message that the syntax "SELECT ... FROM sp@db(param1, param2)" works.
Anyway, even with the PL/SQL block the error message is the same - ORA-00933 "SQL command not properly ended"
and the cursor (* in SQL*PLUS) is put just at the first bracket.
Edited by: user636213 on Aug 10, 2012 5:17 AM -
Table-Valued Function not returning any results
ALTER FUNCTION [dbo].[fGetVendorInfo]
@VendorAddr char(30),
@RemitAddr char(100),
@PmntAddr char(100)
RETURNS
@VendorInfo TABLE
vengroup char(25),
vendnum char(9),
remit char(10),
payment char(10)
AS
BEGIN
insert into @VendorInfo (vengroup,vendnum)
select ks183, ks178
from hsi.keysetdata115
where ks184 like ltrim(@VendorAddr) + '%'
update @VendorInfo
set remit = r.remit
from
@VendorInfo ven
INNER JOIN
(Select ksd.ks188 as remit, ksd.ks183 as vengroup, ksd.ks178 as vendnum
from hsi.keysetdata117 ksd
inner join @VendorInfo ven
on ven.vengroup = ksd.ks183 and ven.vendnum = ksd.ks178
where ksd.ks192 like ltrim(@RemitAddr) + '%'
and ks189 = 'R') r
on ven.vengroup = r.vengroup and ven.vendnum = r.vendnum
update @VendorInfo
set payment = p.payment
from
@VendorInfo ven
INNER JOIN
(Select ksd.ks188 as payment, ksd.ks183 as vengroup, ksd.ks178 as vendnum
from hsi.keysetdata117 ksd
inner join @VendorInfo ven
on ven.vengroup = ksd.ks183 and ven.vendnum = ksd.ks178
where ksd.ks192 like ltrim(@PmntAddr) + '%'
and ks189 = 'P') p
on ven.vengroup = p.vengroup and ven.vendnum = p.vendnum
RETURN
END
GO
Hi all,
I'm having an issue where my Table-Valued Function is not returning any results.
When I break it out into a select statement (creating a table, and replacing the passed in parameters with the actual values) it works fine, but with passing in the same exact values (copy and pasted them) it just retuns an empty table.
The odd thing is I could have SWORN this worked on Friday, but not 100% sure.
The attached code is my function.
Here is how I'm calling it:
SELECT * from dbo.fGetVendorInfo('AUDIO DIGEST', '123 SESAME ST', 'TOP OF OAK MOUNTAIN')
I tried removing the "+ '%'" and passing it in, but it doesn't work.
Like I said if I break it out and run it as T-SQL, it works just fine.
Any assistance would be appreciated.Why did you use a proprietary user function instead of a VIEW? I know the answer is that your mindset does not use sets. You want procedural code. In fact, I see you use an “f-” prefix to mimic the old FORTRAN II convention for in-line functions!
Did you know that the old Sybase UPDATE.. FROM.. syntax does not work? It gives the wrong answers! Google it.
Your data element names make no sense. What is “KSD.ks188”?? Well, it is a “payment_<something>”, “KSD.ks183” is “vendor_group” and “KSD.ks178” is “vendor_nbr” in your magical world where names mean different things from table to table!
An SQL programmer might have a VIEW with the information, something like:
CREATE VIEW Vendor_Addresses
AS
SELECT vendor_group, vendor_nbr, vendor_addr, remit_addr, pmnt_addr
FROM ..
WHERE ..;
--CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
in Sets / Trees and Hierarchies in SQL -
SQL Server Multiple JOINS with Table Value Function - query never ends
I have a query with 4 joins using a table value function to get the data and when I execute it the query never ends.
Issue Details
- Table value function
CREATE FUNCTION [dbo].[GetIndicator]
@indicator varchar(50),
@refDate datetime
RETURNS
TABLE
AS
RETURN
SELECT
T1.Id ,T1.ColINT_1, T1.ColNVARCHAR_1 collate DATABASE_DEFAULT as ColNVARCHAR_1 ,T1.ColNVARCHAR_2 ,T1.ColSMALLDATETIME_1, T1.ColDECIMAL_1, T1.ColDECIMAL_1
FROM TABLE2 T2
JOIN TABLE3 T3
ON T2.COLFKT3 = T3.Id
AND T3.ReferenceDate = @RefDate
AND T3.State != 'Deleted'
JOIN TABLE4 T4
ON T2.COLFKT4 = T4.Id AND T4.Name=@indicator
JOIN TABLE1 T1
ON T2.COLFKT1=T1.Id
- Query
DECLARE @RefDate datetime
SET @RefDate = '30 April 2014 23:59:59'
SELECT DISTINCT OTHERTABLE.Id As Id
FROM
GetIndicator('ID#1_0#INDICATOR_X',@RefDate) AS OTHERTABLE
JOIN GetIndicator('ID#1_0#INDICATOR_Y',@RefDate) AS YTABLE
ON OTHERTABLE.SomeId=YTABLE.SomeId
AND OTHERTABLE.DateOfEntry=YTABLE.DateOfEntry
JOIN GetIndicator('ID#1_0#INDICATOR_Z',@RefDate) AS ZTABLE
ON OTHERTABLE.SomeId=ZTABLE.SomeId
AND OTHERTABLE.DateOfEntry=ZTABLE.DateOfEntry
JOIN GetIndicator('ID#1_0#INDICATOR_W',@RefDate) AS WTABLE
ON OTHERTABLE.SomeId=WTABLE.SomeId
AND OTHERTABLE.DateOfEntry=WTABLE.DateOfEntry
JOIN GetIndicator('ID#1_0#INDICATOR_A',@RefDate) AS ATABLE
ON OTHERTABLE.SomeId=ATABLE.SomeId
AND OTHERTABLE.DateOfEntry=ATABLE.DateOfEntry
Other details:
- SQL server version: 2008 R2
- If I execute the table function code outside the query, with the same args, the execution time is less the 1s.
- Each table function call return between 250 and 500 rows.Hi,
Calling function in general is a costly query. And definitely joining with a function 5 times in not an efficient one.
1. You can populate the results for all parameters in a CTE or table variable or temporary table and join (instead of funtion) for different parameters
2. Looks like you want fetch the IDs falling to different indicators for the same @Refdate. You can try something like this
WITH CTE
AS
SELECT
T1.Id ,T1.ColINT_1, T1.ColNVARCHAR_1 collate DATABASE_DEFAULT as ColNVARCHAR_1 ,T1.ColNVARCHAR_2 ,T1.ColSMALLDATETIME_1, T1.ColDECIMAL_1, T1.ColDECIMAL_1, T4.Name
FROM TABLE2 T2
JOIN TABLE3 T3
ON T2.COLFKT3 = T3.Id
AND T3.ReferenceDate = @RefDate
AND T3.State != 'Deleted'
JOIN TABLE4 T4
ON T2.COLFKT4 = T4.Id AND T4.Name=@indicator
JOIN TABLE1 T1
ON T2.COLFKT1=T1.Id
SELECT * FROM CTE WHERE Name = 'ID#1_0#INDICATOR_X' AND Name = 'ID#1_0#INDICATOR_Y' AND Name = 'ID#1_0#INDICATOR_Z' AND Name = 'ID#1_0#INDICATOR_W' AND Name = 'ID#1_0#INDICATOR_A' AND ReferenceDate = @RefDate.
Or you can even simplify more depends on your requirement.
Regards,
Brindha. -
How to declare variable in table valued function
hello.
i have the following code to define a inline table valued function
but the use of cmn.ReshteId('Lf_WL') as a function in where clause is not good performance.
Alter function lf.fn_WholeLifeBn_GetForm(@ViewKind tinyint, @CurrentLocation int) returns table
as
return
select B.*
from lf.fn_LifeBN_GetForm(@ViewKind, @CurrentLocation) B
where Reshte = cmn.ReshteId('Lf_WL')
for better performance following code is good:
declare @Reshte smallint
set @Reshte = cmn.ReshteId('Lf_TS')
select B.*
from lf.fn_LifeBN_GetForm(@ViewKind, @CurrentLocation) B
where Reshte = @Reshte
but can not use it as the first code block in inline function.
please help for define a good function.What do you think about Multi-Statement Table-Valued UDFs?
create function Func(@Var int)
returns @T table(ColName int)
as
begin
insert into @T(ColName) values (@Var)
return
end
select * from Func(10)
select * from Func(20)
---or
alter function Func()
returns @T table(ColName int)
as
begin
declare @Var int
set @Var = 10
insert into @T(ColName) values (@Var)
return
end
select * from Func()
Best Regards,Uri Dimant SQL Server MVP,
http://sqlblog.com/blogs/uri_dimant/
MS SQL optimization: MS SQL Development and Optimization
MS SQL Consulting:
Large scale of database and data cleansing
Remote DBA Services:
Improves MS SQL Database Performance
SQL Server Integration Services:
Business Intelligence -
SQL CLR Table-Valued Function System.NullReferenceException
Good day.
I wrote a clr table-valued function that gets the data from the sharepoint list using the client model.
Sometimes I get exception (When I calling this function I get 90000 rows and then I get this exception...):
Msg 6260, Level 16, State 1, Line 1
An error occurred while getting new row from user defined Table Valued Function :
System.NullReferenceException: Object reference not set to an instance of an object. System.NullReferenceException: v at SDS.FillRow(Object obj, SqlInt32& month, SqlString& datePlanSalary, SqlString& dilerCode, SqlString& dilerName, SqlString&
model, SqlInt32& countSalary).
How can I fix this issue?
My Code:
public class SDS
[SqlFunction(SystemDataAccess = SystemDataAccessKind.Read, FillRowMethodName = "FillRow")]
public static IEnumerable SDSItems(SqlString url, SqlString listName)
ClientContext context = new ClientContext(url.ToString());
List list = context.Web.Lists.GetByTitle(listName.ToString());
CamlQuery query = new CamlQuery();
query.ViewXml = "<View/>";
ListItemCollection listItems = list.GetItems(query);
context.Load(list);
context.Load(listItems);
context.ExecuteQuery();
return listItems;
public static void FillRow(
object obj,
out SqlInt32 month,
out SqlString datePlanSalary,
out SqlString dilerCode,
out SqlString dilerName,
out SqlString model,
out SqlInt32 countSalary
item = (ListItem)obj;
month = Convert.ToInt32(item["_x041c__x0435__x0441__x044f__x04"]);
datePlanSalary = Convert.ToString(item["_x0414__x0430__x0442__x0430__x000"]);
dilerCode = Convert.ToString(item["_x041a__x043e__x0434__x0020__x04"]);
dilerName = Convert.ToString(item["_x041d__x0430__x0437__x0432__x04"]);
model = ((FieldLookupValue)item["_x041c__x043e__x0434__x0435__x04"]).LookupValue;
countSalary = Convert.ToInt32(item["_x041a__x043e__x043b__x0438__x04"]);That's not a lot of information to go on, but...
Can you put a check in your FillRow method for a null object (or one of your fields being null) and put out diagnostic information? Or is it happening in the ListItemCollection iterator itself? (i.e. before it returns a row back to FillRow). If it's happening
in the iterator, perhaps you could subclass it and return diagnostics at that point.
I'm also wondering (if it actually always happen at row 90000) if you're hitting a limit in web service call, or iterator, or UDF code. Does the function ever return more than 90000 rows successfully?
Hope this helps, Bob -
JDBC Adapter Call a Table-Valued Function
Hello to all,
we're using the JDBC adapter to access a MS SQL-Server 2008.
I have to call a "Table-Valued Function" via JDBC.
Has anybody done this?
I've tried to call it like a stored procedure with the following:
<ns1:LGBuchungSAP_REQ xmlns:ns1="http://xyz.de/pi/mav/kantine">
<fLGBuchungenSAP>
<Tablename action="execute">
<table>dbo.fLGBuchungenSAP</table>
</Tablename>
</fLGBuchungenSAP>
</ns1:LGBuchungSAP_REQ>
but I get following error:
com.sap.engine.interfaces.messaging.api.exception.MessagingException: Error processing request in sax parser:
Error when executing statement for table/stored proc. 'dbo.fLGBuchungenSAP' (structure 'fLGBuchungenSAP'): com.microsoft.sqlserver.jdbc.SQLServerException:
Fehler bei der Anforderung für 'fLGBuchungenSAP' (Prozedur), weil 'fLGBuchungenSAP' ein Tabellenwertfunktion-Objekt ist.
Calling with a select-statement also fails:
<ns1:LGBuchungSAP_REQ xmlns:ns1="http://xyz.de/pi/mav/kantine">
<STATEMENT_NAME>
<Tablename action="SELECT">
<table>dbo.fLGBuchungenSAP('20101101 00:00:00', '20110101 00:00:00')</table>
</Tablename>
</STATEMENT_NAME>
</ns1:LGBuchungSAP_REQ>
with error:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<!-- Eingangs-Message -->
<SAP:Error xmlns:SAP="http://sap.com/xi/XI/Message/30" xmlns:SOAP="http://schemas.xmlsoap.org/soap/envelope/" SOAP:mustUnderstand="1">
<SAP:Category>XIAdapterFramework</SAP:Category>
<SAP:Code area="MESSAGE">GENERAL</SAP:Code>
<SAP:P1></SAP:P1>
<SAP:P2></SAP:P2>
<SAP:P3></SAP:P3>
<SAP:P4></SAP:P4>
<SAP:AdditionalText>com.sap.engine.interfaces.messaging.api.exception.MessagingException: Error processing request in sax parser: Error when executing statement for table/stored proc. 'dbo.fLGBuchungenSAP('20101101 00:00:00', '20110101 00:00:00')' (structure 'STATEMENT_NAME'): java.lang.IndexOutOfBoundsException: Index: 4, Size: 4</SAP:AdditionalText>
<SAP:Stack></SAP:Stack>
<SAP:Retry>M</SAP:Retry>
</SAP:Error>
Please advice
Regards
ChristianHello to all,
I solved the problem.
You have to call it this way:
<ns1:LGBuchungSAP_REQ xmlns:ns1="http://xyzde/pi/mav/kantine">
<STATEMENT>
<LGBuchungSAP action="SQL_DML">
<access>select * from dbo.fLGBuchungenSAP('$DatumVon$', '$DatumBis$')</access>
<key>
<DatumVon>20101101 00:00:00</DatumVon>
<DatumBis>20110101 00:00:00</DatumBis>
</key>
</LGBuchungSAP>
</STATEMENT>
</ns1:LGBuchungSAP_REQ>
But I get the next error: "A result set was generated for the update task"
<SAP:Error xmlns:SAP="http://sap.com/xi/XI/Message/30" xmlns:SOAP="http://schemas.xmlsoap.org/soap/envelope/" SOAP:mustUnderstand="1">
<SAP:Category>XIAdapterFramework</SAP:Category>
<SAP:Code area="MESSAGE">GENERAL</SAP:Code>
<SAP:P1></SAP:P1>
<SAP:P2></SAP:P2>
<SAP:P3></SAP:P3>
<SAP:P4></SAP:P4>
<SAP:AdditionalText>com.sap.engine.interfaces.messaging.api.exception.MessagingException: Error processing request in sax parser: Error when executing statement for table/stored proc. 'LGBuchungSAP' (structure 'STATEMENT'): com.microsoft.sqlserver.jdbc.SQLServerException: Es wurde ein Resultset für den Aktualisierungsvorgang generiert.</SAP:AdditionalText>
<SAP:Stack></SAP:Stack>
<SAP:Retry>M</SAP:Retry>
</SAP:Error> -
SQL: Issue with running out of storage on server when running table-valued function
SQL Version: 2008 (not r2)
Problem: I'm getting the following error message when running a table-valued function:
Msg 1105, Level 17, State 2, Line 1
Could not allocate space for object 'dbo.SORT temporary run storage: 141072001204224' in database 'tempdb' because the 'PRIMARY' filegroup is full. Create disk space by deleting unneeded files, dropping objects in the filegroup, adding additional files
to the filegroup, or setting autogrowth on for existing files in the filegroup.
Request: Could anyone tell me if there are modifications that I could make to my SQL code to avoid this storage issues?
Thanks,
....bob sutor
Code Facts:
The JCCD table is a large table 2MM records
The other tables in the JOINS are very small 15 records or less
SQL Function Code:
ALTER FUNCTION [dbo].[xcft_XAWP_GLBalance_JCCD_Detail]()
RETURNS @JCGLDetail TABLE
JCCo tinyint
, Job varchar(10)
, PostingSource varchar(10)
, CostToDate numeric(12,2)
, Phase varchar(20)
, EarnType smallint
, LiabilityType smallint
, CostType tinyint
, ControllingSetting varchar(30)
, GLAccountCharged varchar(20)
, DeptNum varchar(10)
, DeptDesc varchar(30)
, JCDC_CostType tinyint
, CostTypeGL_Open varchar(20)
, CostTypeGL_Closed varchar(20)
, JCDO_ExcludePR varchar(1)
, JCDO_Phase varchar(20)
, PhaseGL_Open varchar(20)
, PhaseGL_Closed varchar(20)
, JCDL_LiabType smallint
, LiabTypeGL_Open varchar(20)
, LiabTypeGL_Closed varchar(20)
, JCDE_EarnType smallint
, EarnTypeGL_Open varchar(20)
, EarnTypeGL_Closed varchar(20)
AS
BEGIN
DECLARE
@WIPMonthCurrent date
SET @WIPMonthCurrent = (Select TOP 1 WIPMonth FROM udxcWIPMonths WHERE ActiveWIPPeriod = 'Y')
INSERT INTO @JCGLDetail
JCCo
, Job
, PostingSource
, CostToDate
, Phase
, EarnType
, LiabilityType
, CostType
, DeptNum
, DeptDesc
, JCDC_CostType
, CostTypeGL_Open
, CostTypeGL_Closed
, JCDO_ExcludePR
, JCDO_Phase
, PhaseGL_Open
, PhaseGL_Closed
, JCDL_LiabType
, LiabTypeGL_Open
, LiabTypeGL_Closed
, JCDE_EarnType
, EarnTypeGL_Open
, EarnTypeGL_Closed
SELECT
JCCD.JCCo, JCCD.Job, JCCD.Source, sum(JCCD.ActualCost) AS CostToDate, JCCD.Phase, JCCD.EarnType, JCCD.LiabilityType, JCCD.CostType
, JCDM.Department, JCDM.Description
, JCDC.CostType AS JCDC_CostType, JCDC.OpenWIPAcct AS CostTypeGL_Open, JCDC.ClosedExpAcct AS CostTypeGL_Closed
, JCDO.ExcludePR AS JCDO_ExcludePR, JCDO.Phase AS JCDO_Phase, JCDO.OpenWIPAcct AS PhaseGL_Open, JCDO.ClosedExpAcct AS PhaseGL_Closed
, JCDL.LiabType AS JCDL_LiabType, JCDL.OpenBurdenAcct AS LiabTypeGL_Open, JCDL.ClosedBurdenAcct AS LiabTypeGL_Closed
, JCDE.EarnType AS JCDE_EarnType, JCDE.OpenLaborAcct AS EarnTypeGL_Open, JCDE.ClosedLaborAcct AS EarnTypeGL_Closed
FROM JCCD
LEFT JOIN JCJP ON JCCD.JCCo = JCJP.JCCo AND JCCD.Job = JCJP.Job
LEFT JOIN JCCM ON JCJP.JCCo = JCCM.JCCo AND JCJP.Contract = JCCM.Contract
LEFT JOIN JCDM ON JCCM.JCCo = JCDM.JCCo AND JCCM.Department = JCDM.Department
LEFT JOIN JCDC ON JCDM.JCCo = JCDC.JCCo AND JCDM.Department = JCDC.Department AND JCCD.CostType = JCDC.CostType
LEFT JOIN JCDE ON JCDM.JCCo = JCDE.JCCo AND JCDM.Department = JCDE.Department AND JCCD.EarnType = JCDE.EarnType
LEFT JOIN JCDO ON JCDM.JCCo = JCDO.JCCo AND JCDM.Department = JCDO.Department AND JCCD.Phase = JCDO.Phase
LEFT JOIN JCDL ON JCDM.JCCo = JCDL.JCCo AND JCDM.Department = JCDL.Department AND JCCD.LiabilityType = JCDL.LiabType
LEFT JOIN xcft_XAWP_FiscalPeriodCutoffs_ForWIPMonth() AS cutoffs ON JCCD.JCCo = cutoffs.GLCo
WHERE
JCCD.Mth <= cutoffs.FiscalYear_LastMonth
AND JCCD.Job IN(SELECT JobNum FROM budxcWIPData_SQL WHERE WIPMonth = @WIPMonthCurrent)
AND JCCD.JCCo IN(SELECT JCCo FROM JCCO WHERE udExcludeFromWIP <> 'Y' or udExcludeFromWIP IS NULL)
--AND LTRIM(RTRIM(JCCD.Job)) = '71-'
GROUP BY
JCCD.JCCo, JCCD.Job, JCCD.Source, JCCD.Phase, JCCD.EarnType, JCCD.LiabilityType, JCCD.CostType
, JCDM.Department, JCDM.Description
, JCDC.CostType, JCDC.OpenWIPAcct, JCDC.ClosedExpAcct
, JCDO.ExcludePR, JCDO.Phase, JCDO.OpenWIPAcct, JCDO.ClosedExpAcct
, JCDL.LiabType, JCDL.OpenBurdenAcct, JCDL.ClosedBurdenAcct
, JCDE.EarnType, JCDE.OpenLaborAcct, JCDE.ClosedLaborAcct
UPDATE @JCGLDetail
SET
ControllingSetting =
CASE WHEN Phase = JCDO_Phase AND JCDO_ExcludePR = 'N' THEN 'PhaseOverride-PR Excluded'
WHEN Phase = JCDO_Phase AND JCDO_ExcludePR = 'Y'
AND EarnType NOT IN(Select EarnType FROM JCDE WHERE JCDE.JCCo = JCCo AND JCDE.Department = DeptNum)
AND LiabilityType NOT IN(Select LiabType FROM JCDL WHERE JCDL.JCCo = JCCo AND JCDL.Department = DeptNum)
THEN 'PhaseOverride-PR Not Excluded'
WHEN EarnType = JCDE_EarnType THEN 'Earn Type Override'
WHEN LiabilityType = JCDL_LiabType THEN 'Liability Type Override'
ELSE 'Cost Type' END
UPDATE @JCGLDetail
SET
GLAccountCharged =
CASE WHEN ControllingSetting = 'PhaseOverride-PR Excluded' OR ControllingSetting = 'PhaseOverride-PR Not Excluded'
THEN PhaseGL_Open
WHEN ControllingSetting = 'Earn Type Override' THEN EarnTypeGL_Open
WHEN ControllingSetting = 'Liability Type Override' THEN LiabTypeGL_Open
ELSE CostTypeGL_Open END
RETURN
END
Bob Sutorwell, did you either restart the instance or add another tempdb file (no restart required) to let other transactions continue on the server.
or check if autogrowth was limited, change that to unlimnited , to the transactions conintue..
the function may be dumping the data on to tempdb, how much data are you excepting back...what are indexes on the tables
Hope it Helps!! -
Table-Valued function in oracle
Hi All,
I have a table-valued function in MS SQL Server, that I want to convert it.
How can I create table-valued function in Oracle 9.2.0.1.0
Thanks for your thoughtsJust so we are talking the same language, array-type constructs in Oracle are generally known as "collections", while "table" generally refers to a database table. Having said that, you may see references to "PL/SQL Tables" which was the old name for collections when they first came out, although this term has been mostly withdrawn as it's somewhat misleading and causes confusion (that's marketing for you).
Now I think about it we also have table functions, the official name for functions that return collections although IMO almost as misleading. Anyway my rambling point is that "function that returns a table" may cause confusion in Oracle circles. Or maybe it's just me.
There are loads of String To Table examples around:
* www.williamrobertson.net/documents/comma-separated.html
* www.oracle-developer.net/display.php?id=412
Couldn't you have the procedure accept an array in the first place and have something else do the string conversion before it reaches the procedure?
Edited by: William Robertson on Aug 29, 2008 5:39 PM -
Can I disable the wireless functionality and use Ethernet only?
Can you completely disable the wireless functionality and use the Airport Extreme Base Station as a wired internet router with integrated print server?
Yes. I do that. I don't use a print server but I was using that port for an HD. My AExpress connected to it is wired also.
-
Item value as column name in select
Hi,
I have a problem with selecting the columns in the query using items. For example: I have a query:
select column_a from table; or select column_b from table;
and I want to do something like this:
- any item in which I choose the column name
- query: select column_from_item from tale
Is it possible?
My apex version: 4.0.2.00.07
My oracle db version: oracle 11gUnfortunately, it does not work. For example:
I have a table book (title, themes ...), which is eight rows. When I create a static list of items containing the column names (display name and returns the name) and a report based on select according to your design(select :P5_select from table;), you get eight records in the name of the column.
item: select list -> static list -> display value: Title, return value: Title, name: P1_title
select :P1_title from books;
result which i get:
Title
Title
Title
Title -
How to make dynamic query using DBMS_SQL variable column names
First of all i will show a working example of what i intend to do with "EXECUTE IMMEDIATE":
(EXECUTE IMMEDIATE has 32654 Bytes limit, which isn't enough for me so i'm exploring other methods such as DBMS_SQL)
-------------------------------------------------CODE-----------------------------------
create or replace PROCEDURE get_dinamic_query_content
(query_sql IN VARCHAR2, --any valid sql query ('SELECT name, age FROM table')
list_fields IN VARCHAR2) --list of the columns name belonging to the query ( arr_list(1):='name'; arr_list(2):='age';
-- FOR k IN 1..arr_list.count LOOP
-- list_fields := list_fields || '||content.'||arr_list(k)||'||'||'''~cs~'''; )
AS
sql_stmt varchar (30000);
BEGIN
sql_stmt :=
'DECLARE
counter NUMBER:=0;
auxcontent VARCHAR2(30000);
CURSOR content_cursor IS '|| query_sql ||';
content content_cursor%rowtype;
Begin
open content_cursor;
loop
fetch content_cursor into content;
exit when content_cursor%notfound;
begin
auxcontent := auxcontent || '||list_fields||';
end;
counter:=counter+1;
end loop;
close content_cursor;
htp.prn(auxcontent);
END;';
EXECUTE IMMEDIATE sql_stmt;
END;
-------------------------------------------------CODE-----------------------------------
I'm attepting to use DBMS_SQL to perform similar instructions.
Is it possible?Hi Pedro
You need to use DBMS_SQL here because you don't know how many columns your query is going to have before runtime. There are functions in DBMS_SQL to get information about the columns in your query - all this does is get the name.
SQL> CREATE OR REPLACE PROCEDURE get_query_cols(query_in IN VARCHAR2) AS
2 cur PLS_INTEGER;
3 numcols NUMBER;
4 col_desc_table dbms_sql.desc_tab;
5 BEGIN
6 cur := dbms_sql.open_cursor;
7 dbms_sql.parse(cur
8 ,query_in
9 ,dbms_sql.native);
10 dbms_sql.describe_columns(cur
11 ,numcols
12 ,col_desc_table);
13 FOR ix IN col_desc_table.FIRST .. col_desc_table.LAST LOOP
14 dbms_output.put_line('Column ' || ix || ' is ' ||
15 col_desc_table(ix).col_name);
16 END LOOP;
17 dbms_sql.close_cursor(cur);
18 END;
19 /
Procedure created.
SQL> exec get_query_cols('SELECT * FROM DUAL');
Column 1 is DUMMY
PL/SQL procedure successfully completed.
SQL> exec get_query_cols('SELECT table_name, num_rows FROM user_tables');
Column 1 is TABLE_NAME
Column 2 is NUM_ROWS
PL/SQL procedure successfully completed.
SQL> exec get_query_cols('SELECT column_name, data_type, low_value, high_value FROM user_tab_cols');
Column 1 is COLUMN_NAME
Column 2 is DATA_TYPE
Column 3 is LOW_VALUE
Column 4 is HIGH_VALUE
PL/SQL procedure successfully completed.I've just written this as a procedure that prints out the column names using dbms_output - I guess you're going to do something different with the result - maybe returning a collection, which you'll then parse through in Apex and print the output on the screen - this is just to illustrate the use of dbms_sql.
best regards
Andrew
UK -
How to insert data in the table without join and using mapped rule value
1.Table SOL_K
A B C D – Columns Name
C D A B –Coulmns Values Defined (Rule --- Defined)
2.SECOND table SIC_K
SIC_ K
A B C D
Kamal Micky NULL MANOJ
3 Table SIC_Mapping
Same Columns A B C D based On Table SOL_K defined rule
I want to insert values(from table SIC K) into table SICMapping Table with the help of first table(SOL_K)(mapped rule)
Required Result SIC_Mapping Table
The output will be come like this.
A B C D — Columns Name
NULL MANOJ Kamal Micky ---- Came based on defined Mapping RuleWhat's your database version?
That's a funny requirement.
How about :
select case sol.a
when 'A' then sic.a
when 'B' then sic.b
when 'C' then sic.c
when 'D' then sic.d
end as a
, case sol.b
when 'A' then sic.a
when 'B' then sic.b
when 'C' then sic.c
when 'D' then sic.d
end as b
, case sol.c
when 'A' then sic.a
when 'B' then sic.b
when 'C' then sic.c
when 'D' then sic.d
end as c
, case sol.d
when 'A' then sic.a
when 'B' then sic.b
when 'C' then sic.c
when 'D' then sic.d
end as d
from sol_k sol, sic_k sic
;XQuery can do the trick too :
SQL> SELECT *
2 FROM XMLTable(
3 'for $i in ora:view("SIC_K")/ROW
4 return element r {
5 for $j in ora:view("SOL_K")/ROW/child::*
6 return element {name($j)} {$i/child::*[name()=$j]/text()}
7 }'
8 columns
9 a varchar2(30) path 'A'
10 , b varchar2(30) path 'B'
11 , c varchar2(30) path 'C'
12 , d varchar2(30) path 'D'
13 );
A B C D
MANOJ Kamal Micky
Edited by: odie_63 on 29 juin 2011 22:07 -
Direct Print smartform to printer via JOB_OPEN function and using SUBMIT
Hello,
I can not able to printout from forms . I can able to get spool number but it is not printing directly to printer (printer Output should come automatic). I am getting error message in SP02 as Status ->Waiting when i check is showing as "Frontend unavailable".
please find sample code below to test same:
REPORT ZTEST_1 .
constants : wc_x type c value 'X'.
DATA: wv_val(1) TYPE c,
wv_pripar TYPE pri_params,
wv_arcpar TYPE arc_params,
wv_lay TYPE pri_params-paart value 'DINA4',
wv_lines TYPE pri_params-linct,
wv_rows TYPE pri_params-linsz.
data: wv_jobname like tbtcjob-jobname.
data: wv_jobcount like tbtcjob-jobcount,
wv_host like msxxlist-host.
data: begin of ws_starttime.
include structure tbtcstrt.
data: end of ws_starttime.
data: wv_starttimeimmediate like btch0000-char1 value 'X',
wv_flag(1),
WV_DO_PRINT type i.
concatenate sy-tcode+0(4) ' ' 'sample test - print'
into wv_jobname.
*Job open
call function 'JOB_OPEN'
exporting
delanfrep = 'X'
jobname = wv_jobname
sdlstrtdt = sy-datum
sdlstrttm = sy-uzeit
importing
jobcount = wv_jobcount
if sy-subrc eq 0.
CALL FUNCTION 'GET_PRINT_PARAMETERS'
EXPORTING
in_archive_parameters = wv_arcpar
in_parameters = wv_pripar
LIST_NAME = 'JOB NAME'
LIST_TEXT = 'test_text'
RECEIVER = sy-uname
IMMEDIATELY = wc_x
RELEASE = wc_x
USER = sy-uname
layout = wv_lay
no_dialog = wc_x
IMPORTING
out_archive_parameters = wv_arcpar
out_parameters = wv_pripar
valid = wv_val
break-point.
wv_pripar-PRSAP = space.
wv_pripar-PRIOT = 1.
wv_pripar-prrec = sy-uname.
if not wv_val is initial.
*call external program and pass data
submit SF_EXAMPLE_01
USER sy-uname
via job wv_jobname
number wv_jobcount
TO SAP-SPOOL
SPOOL PARAMETERS wv_pripar
ARCHIVE PARAMETERS wv_arcpar
WITHOUT SPOOL DYNPRO
AND RETURN.
endif.
*Close job
ws_starttime-sdlstrtdt = sy-datum .
ws_starttime-sdlstrttm = sy-UZEIT.
ws_starttime-IMSTRTPOS = WC_X .
call function 'JOB_CLOSE'
exporting
event_id = ws_starttime-eventid
event_param = ws_starttime-eventparm
EVENT_PERIODIC = space
jobcount = wv_jobcount
jobname = wv_jobname
laststrtdt = ws_starttime-laststrtdt
laststrttm = ws_starttime-laststrttm
prddays = 0 "set to 0 not repeat
prdhours = 0
prdmins = 0
prdmonths = 0
prdweeks = 0
sdlstrtdt = ws_starttime-sdlstrtdt
sdlstrttm = ws_starttime-sdlstrttm
strtimmed = wv_starttimeimmediate
endif.Hi,
As far as printing to devices not all devices support Bluetooth. Many devices support Bonjour protocal, IPP. The main print port is 9100. Additionally you can see what IO protocols are supported on a product by looking at the EWS (Embedded WebServer) there should be a networking page with that information. Port 9100 is your basic print port and different devices will support different formats (PDF, JPEG, PCL5, PCL6). If there is an API you can find (i am not familiar with J2ME availible calls, then you can use those and send the data to port 9100. Again that is the basic path most printers will accept. not all devices support bonjour not all device support bluetooth etc... Hope that helps and good luck.
I am an HP Employee.
Maybe you are looking for
-
Oracle 8.1.7 on AIX 5.3
I have existing Oracle Database 8.1.7 running on AIX 5.2. My plan is to install 11g Software as different ORACLE_HOME and upgrade 8.1.7 to 11g Based on 11g documentation looks like it only works with AIX 5.3 . So my question is if we upgrade AIX leve
-
Using my Macbook as a monitor for my telescope
Any tips for using my connecting my Macbook to my telescope and using it as a monitor for my telescope images, I have a meade with a video out, but I'm new to Macs, and am not sure on where to even start on setting it up. Thanks
-
Redirect EP to a different backend environment
Does any have the documentation to show the steps required to redirect a Java Stacked EP 7.0 system running ESS/MSS where the security is provided on the backend ABAP ECC environment? Is the only thing to really change the JCO configuration? Vincent
-
Headphones not working with my ipod
How do I get my headphones to work with my ipod?
-
Help on how to change or edit bundle identifier
Good day all, please i want to change the bundle id in itune connect where am editing application info, but i can't see the new bundle id i want to use and i need help on this please, where do i start from.