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.

Similar Messages

  • 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 Sutor

    well, 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!!

  • 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

  • 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(&apos;20101101 00:00:00&apos;, &apos;20110101 00:00:00&apos;)</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
    Christian

    Hello 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(&apos;$DatumVon$&apos;, &apos;$DatumBis$&apos;)</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>

  • 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

  • Create a table in SQL Server, Export tables from Microsoft Excel to Microsoft SQL Server, Populate the created table

    Hello team,
    I have a project that I need to do, what is the best approach for each step?
    1- I have to create a table in Microsoft SQL Server.
    2- I have to import data/ tables from Microsoft Excel or Access to Microsoft SQL Server. Should I use Microsoft Visual Studio to move data from Excel or Access?
    3-I should populate the created table with the data from the exported data.
    4-How should I add the second and third imported table to the first table? Should I use union query?
    After I learn these, I will bring up the code to make sure what I do is right.
    Thanks for all,
    Guity
    GGGGGNNNNN

    Hello Naomi,
    I have imported all the tables into SQL Server,
    I created a table:
    CREATE
    TABLE dbo.Orders
    Now I want to populate this table with the values from imported tables, will this code take care of this task?
    INSERT INTO dbo.Orders(OrderId, OrderDate)
    SELECT OrderId, OrderDate
    FROM Sales.Orders
    UNION
    SELECT OrderId, OrderDate
    FROM Sales.Orders1
    Union
    SELECT OrderId, OrderDate
    FROM Sales.Orders2
    If not, what is the code?
    Please advise me.
    GGGGGNNNNN
    GGGGGNNNNN

  • 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

  • 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 thoughts

    Just 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

  • How to change stored procedure with Table Valued Parameter

    I am not sure how to change the normal stored procedure with Table Value Parameter.Do I have to create a separate Table or do I have to create a datatype. Can you please help me with this
    ALTER PROCEDURE [dbo].[uspInsertorUpdateINF]
    @dp_id char(32),
    @dv_id char(32),
    @em_number char(12),
    @email varchar(50),
    @emergency_relation char(32),
    @option1 char(16),
    @status char(20),
    @em_id char(35),
    @em_title varchar(64),
    @date_hired datetime
    AS
    BEGIN
    SET NOCOUNT ON;
    MERGE [dbo].[em] AS [Targ]
    USING (VALUES (@dp_id, @dv_id , @em_number, @email, @emergency_relation, @option1, @status, @em_id, @em_title, @date_hired))
    AS [Sourc] (dp_id, dv_id, em_number, email, emergency_relation, option1, status, em_id, em_title, date_hired)
    ON [Targ].em_id = [Sourc].em_id
    WHEN MATCHED THEN
    UPDATE
    SET dp_id = [Sourc].dp_id,
    dv_id = [Sourc].dv_id,
    em_number = [Sourc].em_number,
    email = [Sourc].email,
    emergency_relation = [Sourc].emergency_relation,
    option1 = [Sourc].option1,
    status = [Sourc].status,
    em_title = [Sourc].em_title,
    date_hired = [Sourc].date_hired
    WHEN NOT MATCHED BY TARGET THEN
    INSERT (dp_id, dv_id, em_number, email, emergency_relation, option1, status, em_id, em_title,date_hired)
    VALUES ([Sourc].dp_id, [Sourc].dv_id, [Sourc].em_number, [Sourc].email, [Sourc].emergency_relation, [Sourc].option1, [Sourc].status, [Sourc].em_id, [Sourc].em_title, [Sourc].date_hired);
    END;

    It's not clear how you would change the procedure. But assuming that you want to replace the existing scalar parameters with tabular input, this is how you would do it. You first create a table type:
    CREATE TYPE  Insertor_type AS TABLE
        (dp_id                char(32),
         dv_id                char(32),
        em_number            char(12),
        email                varchar(50),
        emergency_relation   char(32),
        option1              char(16),
        status               char(20),
        em_id                char(35),
        em_title             varchar(64),
        date_hired           datetime)
    Then you change the procedure header:
    ALTER PROCEDURE [dbo].[uspInsertorUpdateINF] @tvp Insertor_type READONLY AS
    And finally you change the USING clause:
       USING (SELECT dp_id, dv_id , em_number, email, emergency_relation, option1, status, em_id, em_title, date_hired
              FROM   @tvp) AS [Sourc] ON [Targ].em_id = [Sourc].em_id
    The rest is fine as it is.
    Erland Sommarskog, SQL Server MVP, [email protected]

  • How to let sql server 2008 know the table created at front end in c#

    How to let sql server 2008 know the table created at front end in c#

    The best solution is to create table type and pass the DataTable as table-valued parameter. I have an article on my web site about this:
    http://www.sommarskog.se/arrays-in-sql-2008.html
    The full article is a bit of overkill for what you are doing right now, but just the few first pages should get you going.
    Erland Sommarskog, SQL Server MVP, [email protected]

  • Join columns of outer join with table have no uniqueness cons

    Hi! I'm getting noizy error in alert log from time to time:
    Join columns of outer join with table <table_name> have no uniqueness constraints
    I've collected all the queries (v$sql, all_source) with montioned table, but non of them produces that error if executed.
    Any hints how to reproduce this error or where else to search that buggy sql join?
    Edited by: user545083 on 25.10.2010 6:21

    Hi
    I think this error is output via an materialized view refresh - check for mviews against the given table which fulfil the issue given in the error text.
    Thanks
    Paul

  • Can a SQL Server stored procedure call an SAP function module?

    Can a SQL Server stored procedure call an SAP function module.? The stored procedure will be called via a trigger when data records are added to a Z table.

    You have two options:
    - the other software can use the RFC SDK and call directly in the system
    - the other software can use a database connect
    Markus

  • Can I recover a damaged SQL Server 2008 database with the undamaged .mdb and .ldf files?

    Their original SQL Server was 2008, with SP unknown, but installed on D: and C: drives.  The power spike corrupted their O/S on the C:
    drive and someone reinstalled both the O/S and the SQL Server, which is now SQL 2008, SP4.  They have intact files for all system databases, both .mdb and .ldf.  Is there some way they can reconnect with the user databases using the intact copies
    of the previous system databases? I have heard that if the SQL Server is stopped, previous Master and Msdb .mdb and .ldf files moved into place and the server restarted, that any previous user database .mdb and .ldf files can be accessed by the SQL server.
    Is this the case, or are there details missing?

    Hello! try this steps
     1 Open your SQL Server Management Studio console. This application shortcut is available in the SQL Server directory in the Windows Start button.
    2  Enter the system administrator user name and password. SQL Server's administrator user name is "sa." This account is required for privileges to restore the database. If your restoring on a host provider server, use the administrator user name
    and password they supplied for your account.
     3 Right-click your database name and select "Attach." In the new window that opens, click the "Add" button to open a dialog box.
     4 Select your MDF file and press the "Ok" button. It may take several minutes to restore the database if it is a large file. Once the process is finished, browse your tables to verify the data. The database is now restored.
    If nothing helped try to use: 
    https://www.youtube.com/watch?v=1cbOYdvBW2c

Maybe you are looking for

  • Problem Event Name:_APPCRASH osk.exe(on screen keyboard)

    Hi there everyone.Anyone out there can help me with this problem? Many thanks in advance. :) Problem signature:   Problem Event Name: APPCRASH   Application Name: osk.exe   Application Version: 6.3.9600.17031   Application Timestamp: 53087e42   Fault

  • Using a counter channel as a DO

    Hello, Could you please tell me if there is any possible way to use a ctr channel of an 6212 OEM as a DO channel. Thank you in advanced

  • XML Namespace Question

    Hi folks, I'm new to XML, and have been trying to validate an XML document against a schema using an online validator. I have given ultra-simple examples of my schema and document below: Schema <?xml version="1.0"?> <xs:schema xmlns:xs="http://www.w3

  • Change Customer BAPI

    Hello Everyone, I'm calling BAPI, BAPI_CUSTOMER_CREATEFROMDATA1 from a webpage to create an internet cusotmer in SAP.  I'm populating the PERSONAL_DATA structure.  This call works fine and the cusotmer is created.  However, when I call BAPI_CUSTOMER_

  • WBS Element in HR Master Data

    Dear Friends, I have a problem relating to WBS assignment as follows: When a new project is created in PS, some of the existing employees will be assigned to New WBS in PS. I am able to see the list of the employees assigned to the particular WBS. Bu