Scalar subqyery

Hi Folks ,
I have a requirement wherein i need to write a sql statement .Something like
select
col1,
col2,
col3,
col4,
col5,
(select id from is_table),-------i have to optimize this call
col6,
col7
from
table_with_ten_million_rows
I am skeptical of the term used in my subject .i.e. scalar subquery  .i.e. when i am fetching the id from the id_table. But what should be the best way to execute this query .There is no plsql  usage.Is there any way out by which oracle will optimize the call to table is_table  for each and every row scanned .Will a deterministic function work better ? or this scalar subquery ? Or any other way .
Thanks

You really should read until the end the Article Karthick reffered to.
As you can see in the deterministic function in Listing 4, the number of calls is reduced, but only down to 8,316. The scalar subquery cache in this case was better than just marking the function as deterministic. (Note: Marking a function deterministic affects caching only in Oracle Database 10g and above; you will see no change in the number of calls in Oracle9i Database with deterministic functions.)

Similar Messages

  • How to change the width of the database-scalar data type

    I have a new problem. I have a parameter F_Organization in my report(version 6i) of type Database-scalar. now that the width is fixed in property pallete. Is there any way to change the width of this parameter,if so how. will some one let me know

    I did the same, opened the data model typed some dummy character and then deleted them, if u give the alias for the source it does not change the width, instead if u give the original name as the source it changes the width. I do not know why is this happening?
    Message was edited by:
    user552442

  • Why Scalar Subquery expression cannot be used in HAVING clauses?

    Hi All,
    I'm new to SQL. I'm confused with Scalar Subquery.
    Is there anyone who can answer me why Scalar Subquery expression cannot be used in HAVING clauses.
    Can you show me a example?
    Thanks very much,
    Xianyi.Ye
    Edited by: 908428 on 2012-1-16 下午7:24

    Hi,
    908428 wrote:
    Hi Frank,
    Thank you for your quick reply. I also agree with your point.
    But when I read the book, "OCA Oracle Database SQL Certified Expert Exam Guide",( link to illegal copies of book removed by moderator )
    on Page 359, it said that
    Scalar subquery expressions cannot be used in the following locations:
    1. In CHECK constraints
    2. In GROUP BY clauses
    3. In HAVING clauses
    4. In a function-based index (which is coming up in Chapter 11)
    5. As a DEFAULT value for a column
    6. In the RETURNING clause of any DML statement
    7. In the WHEN conditions of CASE
    8. In the START WITH and CONNECT BY clauses, which we discuss in
    Chapter 16.7 and 8 are wrong. Scalar sub-queries can be used in WHEN conditions and START WITH and CONNECT BY clauses. (At least in Oracle 10.2. Is the book based on some earlier version?)
    Edited by: BluShadow on 17-Jan-2012 09:08

  • An array and scalar values together in an sql statement

    Hi
    We have a table called SERVICE and following are the 3 columns from SERVICE table,
    SERVICESTATUSID - NUMBER(10)
    ACCOUNTID - NUMBER(10)
    SERVICENUMBER - VARCHAR(41)
    My aim is to be able to update the status of a bunch of entries in this table from Pro C code with new ServiceStatusID where accountId matches the accountId supplied and SERVICENUMBER exists in the list of services supplied.
    Now I am trying to use host arrays here for SERVICENUMBERs and then my Update statement looks like this,
    UPDATE SERVICE SET SERVICESTATUSID = :x WHERE ACCOUNTID = :y AND SERVICENUMBER = :z
    And then I am trying to execute it with the help of bind variables in Pro C as follows,
    EXEC SQL AT DB_NAME CONTEXT USE :myContext;
    EXEC SQL AT DB_NAME DECLARE sqlStatement STATEMENT;
    EXEC SQL AT DB_NAME PREPARE sqlStatement FROM :str;
    EXEC SQL AT DB_NAME EXECUTE sqlStatement USING :statusId, :accountId, :serviceNumbersList;
    where statusId is integer,

    user12169137 wrote:
    Now I am trying to use host arrays here for SERVICENUMBERs and then my Update statement looks like this,
    UPDATE SERVICE SET SERVICESTATUSID = :x WHERE ACCOUNTID = :y AND SERVICENUMBER = :z
    And then I am trying to execute it with the help of bind variables in Pro C as follows,
    EXEC SQL AT DB_NAME CONTEXT USE :myContext;
    EXEC SQL AT DB_NAME DECLARE sqlStatement STATEMENT;
    EXEC SQL AT DB_NAME PREPARE sqlStatement FROM :str;
    EXEC SQL AT DB_NAME EXECUTE sqlStatement USING :statusId, :accountId, :serviceNumbersList;
    where statusId is integer,I am not sure what you are asking. I think you want statusId to be a scalar integer but use a series of values for the service numbers.
    This can be done, but will take a little effort. It might be most easily done in a PL/SQL block where you can control the datatypes too. What you will have to do is create a database object with the datatype (integer, number, whatever), then another object as a table of that object. It should then be possible to convert your collection into a database nested table with the CAST() function. Don't expect really good performance from this.
    Search OTN for cast conversions for more information on this method.
    Another alternative if you have < 1000 items is to use dynamic SQL by generating an IN list from your collection contents. Again, performance will probably not be great.
    Good luck.

  • SQL*Modeler - creation of VARRAY or Collection Type of scalar type errors

    In SQl*Modeler 2.0.0 Build 584, I can create either VARRAY or Collections. These work fine for usre defined structured types but I encounter huge problems when I use a simple scalar type of number or varchar2.
    For instance I create a new collection type, give it a name, specify its a collection (or VARRAY, same problem) then click datatype. On the select Data type box I select logical type. A new window opens, I select VARCHAR from the drop down list.
    Enter the size 15, everything appears fine. I click OK, the select data type screen now shows a logical type of VARCHAR(15).
    So far I'm happy. I generate the DDL, everthing is fine, the DDL contains my collection of VARCHAR2(15).
    Now I save the model, close it and re-open the same model. My collection is now of VARCHAR so the next time I generate it will get an error because the syntax is wrong because it has no length. Same problem happens when selecting a NUMBER, looses the precision and scale but at least that command still works, just with a maximum numeric value.
    Ok, so lets try creating distinct types. Why we can't access domains when specifying types from here remains a mystery to me.
    So I create a distinct type Varchar2_15 which is of Logical type VARCHAR and give it a size. Similarly, create another distinct type of NUMERIC_22_0 precision 22 scale 0. This seems to get around the problem of losing the data but the DDL generated shows the datatype to be either VARCHAR (not VARCHAR2) and NUMERIC(22), not number(22). Now I know that VARCHAR currently maps to VARCHAR2 but isn't guaranteed to in the future (even though its been like that since V6) and NUMERIC is just an alias for NUMBER but its going to confuse a lot of java people and its totally inconsitent and just plain wrong.
    Any suggestions or workarounds will be gratefully received.
    Ian Bainbridge

    Hi Ian,
    I see a bug in save/load of collection types and as result no size or precision and scale information. It's fixed in new release.
    However I cannot reproduce the problem with distinct types - I have them generated as varchar2 and number (this is for Oracle).
    You can check:
    - database you use in DDL generation - I got varchar and numeric for MS SQL Server;
    - mapping of logical types VARCHAR and NUMERIC to native types in "Types Administration".
    Philip
    PS - I was able to reproduce it - I looked at wrong place - DDL generation for collection types is broken - it's ok for columns. I logged bug for that.
    Edited by: Philip Stoyanov on Jun 28, 2010 8:55 PM

  • Stored Proc with SSRS multi value parameter gives " Must Declare scalar Varaiable @StateID

    Hi All,
    I have one stored proc with @fromDate , @Todate and multivalue input
    parameter@StateID of type integer.
    When I run below stored proc via SSRS by selecting multiple values thru multiValue parameter into @StateID...it gives error saying "Must Declare scalar variable @StateID"
    Not sure what is wrong with the input parameters.
    ID is Integer type in all the 3 tables - dbo.EastCities, dbo.WestCities  , dbo.Country
    I need help fixing this  "Must Declare scalar variable @StateID" error
    This is the UDF split() I am using..
    Function:
    CREATE FUNCTION dbo.SplitStateID
    (    @List VARCHAR(MAX))
    RETURNS TABLE
    AS   
    RETURN   
    (        SELECT DISTINCT [Value] = CONVERT(INT, LTRIM(RTRIM(CONVERT( VARCHAR(12),SUBSTRING(@List, Number, CHARINDEX(',', @List + ',', Number) - Number))))
     FROM  dbo.Numbers       
     WHERE Number <= CONVERT(INT, LEN(@List))AND SUBSTRING(',' + @List, Number, 1) = ','    );
     GO
     SELECT [Value] FROM dbo.SplitStateID('10,30,50');
    Also, I have created dbo.Numbers table which is used in udf..
    reference url -- > 
    http://sqlblog.com/blogs/aaron_bertrand/archive/2009/08/01/processing-a-list-of-integers-my-approach.aspx
    SET NOCOUNT ON;
    DECLARE @UpperLimit INT;
    SET @UpperLimit = 10000;
    WITH n AS(   
    SELECT        rn = ROW_NUMBER() OVER        (ORDER BY s1.[object_id])   
    FROM sys.objects AS s1   
    CROSS JOIN sys.objects AS s2   
    CROSS JOIN sys.objects AS s3)
    SELECT [Number] = rn - 1
    INTO dbo.Numbers FROM n
    WHERE rn <= @UpperLimit + 1;
    CREATE UNIQUE CLUSTERED INDEX n ON dbo.Numbers([Number]);
    Stored procedure:
    Create Procedure dbo.CountrySelection
    ( @FromDate Date, @ToDate Date, @StateID Int)
    AS
    BEGIN
    set nocount on;
    SELECT * INTO #EastCities
    FROM (
    SELECT ID,Description from dbo.EastCities
    Where ID IN (SELECT Value from dbo.SplitStateID(@StateID))
    ) AS A
    SELECT * INTO #WestCities
    FROM (
    SELECT ID,Description from dbo.WestCities
    Where ID IN (SELECT Value from dbo.SplitStateID(@StateID))
    ) AS B
    SELECT * INTO #Country
    FROM (
    SELECT ID , Description, State,Country From dbo.Country
    ) AS C
    SELECT EC.ID AS East, WC.ID AS West , EC.Description AS EastDesc, WC.Description AS WestDesc, CT.State, CT.Country
    FROM #Country CT
    LEFT JOIN #EastCities EC ON CT.ID=EC.ID
    LEFT JOIN #WestCities WC ON CT.ID=WC.ID
    DROP TABLE #EastCities
    DROP TABLE #WestCities
    DROP TABLE #Country
    END
    Above 3 temp tables are joined by #Country.ID key
    It works fine when single value is passed in @StateID
    Exec dbo.CountrySelection '01/01/2010','02/01/2010',10
    It fails when multi value passed into @StateID
    Exec dbo.CountrySelection '01/01/2010','02/01/2010','10,30,40'
    SSRS error log shows "Must declare scalar variable @StateID"
    Need help in fixing this issue.
    Thanks,
    RH
    sql

    Visakh,
    I changed @StateID date type to varchar(max) and still I get this error.  
    System.Data.SqlClient.SqlException: Must declare the scalar variable "@StateID".
       at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection)
       at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj)
    I am running this SO in SSRS quert Type =Text
    Actually sp created on db2 database and due to some limitations I am running(via SSRS) this from different db1 database data source within the same db server. When I run this sp from SSRS query designer(edit query designer button) and pass
    multivalue parameters to @StateID as 10 , 20 it works and gives expected resultset.
    Thanks,
    RH
    sql

  • How to convert a scalar variable into a 1-D length N array?

    Hi guys,
    I am new in Labview. I use Labview to accquire the output data from a measurement circuit with RS232 bus. The result needs some mathematical operation to have a meaningful number. After this operation the result is a scalar variable that is changing as new data read from my circuit. I want to see the power spectrum of this signal so tried to use FFT block (Labview 6.1, signal processing->frequency domain->real fft / power spectrum). However because the fft block needs 1-D array type of data as input, I can not just connect my result to the fft block. The error it gives me is:
    These cannot be wired together because their data types (numeric,
    string, array, cluster, etc.) do not match. Show the Context Help
    window to see what data type is required.
    The type of the source is double [64-bit real (~15 digit precision)].
    The type of the sink is 1-D array of double [64-bit real (~15 digit precision)].
    So I guess I have to do something to convert my result into a 1-D array with a length N, which is the number of data I use for one FFT transform. But the question is how.
    I pass the data directly through a For-loop, the result is a 1-D array with all the members having the same value as the input value(my calculated result). Then next time a new result come in, all of the members of that array changes to the new value.
    Please help!

    Hi nano,
    "So I interpret that as putting the for loop (the subVI) in another for loop?" - Yes, correct.
    See example! (Also on better using LV primitives.)
    Where is this "vsource control block"?
    Message Edited by GerdW on 03-02-2009 11:24 PM
    Best regards,
    GerdW
    CLAD, using 2009SP1 + LV2011SP1 + LV2014SP1 on WinXP+Win7+cRIO
    Kudos are welcome
    Attachments:
    example.vi ‏20 KB

  • Could not able to show a scalar value in Page Header/Group Header of the re

    Hi,
    I could not able to show a scalar value in Page Header/Group Header of the report which is returned from Sub-report. But I am able to display it in both Group Footer and Page Footer.
    I used shared variable in formula filed of both main and sub report and both are placed in the main and sub-report.
    Please do needful.
    Thanks & Regards,
    Mani G.S.

    You can only show Shared variables in main report in a location after the subreport has executed.
    If you want to show values in page header or group header you must place subreport in a section above these. This is unlikely to be possible so you will have to live with displaying results in Group/page footer.
    Alternatively you can execute subreport twice, once where subreport is hidden in a section above page/group header and pass summary figure you require and then again where you currently have subreport so you can see details as required.
    Ian

  • How do I get an interpolat​ed scalar value from a 2D lookup table z=f(x,y)?

    I have a table of numerical values.  Rows correspond to discrete values of a parameter, columns to discrete values of a second parameter.  I want tin interpolate a scalar value from the table :
    Table Z = f(X,Y)
    find Zi,j corresponding to specified X and Y values (which may not be the exact discrete valuescorresponding to rows and columns).
    So, I want to find Z(1.5, 3) from a table
        X    1      2     3
    Y
    2       10   15    20
    4        50   60   70
    The results would be Z = 33.75
    The LUT routines interpolate an entire table rather than giving a single answer.  earlier discussions have posted routines that find the nearest table entry but do not interpolate between entries.
    This sounds very simple....
    Thanks.

    Have a look at the bilinear interpolation examples quoted in the various links of this idea.
    (Use threshold array to get the fractional array index from the axis mapping)
    LabVIEW Champion . Do more with less code and in less time .

  • Scalar Select stmt in Case causing problems

    Hello,
    here is some background followed by my question
    I have two tables, headerx and detailx which are joined
    Detailx has a sequence number column
    I would like to query detailx such that if for any header there are more than one details, it should return the highest sequence with state = passed.
    If there is only one detail, then it should return that detail row.
    So, I came up with this SQL:
    select DTL.ID, DTL.TSTAMP
    from HEADERX hdr inner join
         DETAILX dtl on DTL.HDR_FK = hdr.id
    where dtl.seq =
         (select case max(seq) when 1 then 1
                                       else (select max(seq) from DETAILX dtl3 where dtl3.hdr_fk = hdr.id and dtl3.state='PASSED')
                                       end
           from DETAILX dtl2
           where dtl2.hdr_fk = hdr.id)
    ; The above threw a ORA 937 - Not a single-group group function
    If I remove the embedded select inside the case and replace it with an arbitrary value, there is no error and some rows are returned
    select DTL.ID, DTL.TSTAMP
    from HEADERX hdr inner join
         DETAILX dtl on DTL.HDR_FK = hdr.id
    where dtl.seq =
         (select case max(seq) when 1 then 1 else 2 end from DETAILX dtl2 where dtl2.hdr_fk = hdr.id)
    ; Not really understanding why, I added a group by which appears to work
    select DTL.ID, DTL.TSTAMP
    from HEADERX hdr inner join
         DETAILX dtl on DTL.HDR_FK = hdr.id
    where dtl.seq =
         (select case max(seq) when 1 then 1
                                        else (select max(seq) from DETAILX dtl3 where dtl3.hdr_fk = hdr.id and dtl3.state='PASSED')
                                        end
          from DETAILX dtl2
          where dtl2.hdr_fk = hdr.id
          group by 1)
    ; Question: Why is the group by required? Clearly there is only one scalar value that will be returned
    If anyone cares to suggest, is there a more elegant solution?

    Instead of joining the same table too many times,
    You can do this,
    Not tested,
    SELECT DTL.ID, DTL.TSTAMP
      FROM    HEADERX hdr
           INNER JOIN
              (SELECT dtl.*, CASE WHEN MAX (seq) OVER (PARTITION BY ID) = 1
                                  THEN 1
                                  ELSE MAX (DECODE (state, 'PASSED', seq)) OVER (PARTITION BY ID)
                              END mx
                 FROM DETAILX dtl) dtl
           ON (DTL.HDR_FK = hdr.ID
           AND hdr.seq = dtl.mx)
    G.

  • Save scalar ascii data to columns

    Hello,
    I have created a signal express project (signalexpress 2.0) that creates 60 second averages of data coming in over an NI USB-6251.  It runs through a conditional repeat of aquire steps until a generated signal (time) reaches 60 seconds.  This part of the workbench seems to function fine, but the final step is to save the resulting scalar data to an ascii file - and the output is not in a normal column format. 
    Each time I hit the "run once" button, I would like a row of data to be appended to the ascii file - with each channel under the appropriate channel name (in the appropriate column).  Instead, I get an output that has channel names in each column, followed by a line of string output for each channnel.  You can see the output in the attached "NewTest1.txt" file.
    The project is also attached.  Rename ".txt" to ".seproj" to open it.
    Any suggestions?
    Attachments:
    NewTest1.txt ‏2 KB
    ProjectFile.txt ‏77 KB

    Hi,
    I believe this is a bug in SignalExpress in this situation, so I filed a bug report to have them look into it.
    In the meantime (and I realize this is not the ideal solution for you), I created a LabVIEW VI that you can call from SignalExpress using the "Run LabVIEW VI" step. I wrote this VI using the User-Step template which is included with SignalExpress, and using LabVIEW 7.1, not knowing which version of LabVIEW you might have, if any, should you want to modify the VI.
    To use this VI, replace the Save To ASCII step that you have and call the top-level VI in the LLB included below. Since the VI doesn't have access to the names of the inputs, I had to include an array of string which you'll have to write the names of your inputs in. I hardcoded it to have a maximum of 7 inputs like in the project you provided.
    I hope this helps until the bug if actually fixed. Please reply if you have any questions regarding the attached files.
    Phil
    Attachments:
    SaveToASCII2.llb ‏73 KB

  • HTMLDB_ITEM with scalar subqueries

    How does HTMLDB_ITEM work with scalar subqueries?
    Suppose I want to do something like
    select
    c1,c2,c3,
    (select htmldb_item.checkbox(1,c4)
    from sometable where ....)
    from ...
    If the scalar subquery doesnt return a row, I dont get my checkbox.
    How else can I do this? Thanks

    Sort of. Let me try to explain what I am really trying to do.
    create table class
    class_id int primary key,
    class_name varchar2(25),
    class_start_date date,
    class_end_date date
    create table students
    student_id int primary key,
    sname varchar2(25),
    address varchar2(25)
    create table attendance
    student_id int,
    class_id int,
    registered varchar2(1) not null check (registered in ('Y','N')),
    reg_date date
    Given a list of students and a list of classes,I want to put up a updatable form on the attendance table. If a record exists in the attendance table, I should be able to upadte it. If it doesnt exist, the fields (registered and reg_date) should still be shown and if I enter a value in them, create the row (otherwise dont create the row!)
    How can I do this? Thanks

  • Getting "Must declare the scalar variable" Error

    Hello All,
    I have write following query to block invoice which has Prices not equal to PriceList as below.
    -- To Block Invoices which has Prices not equal to PriceList
    IF (@transaction_type='A' OR @transaction_type = 'U') AND CAST(@OBJECT_TYPE = '18')
    BEGIN
        SELECT T1.ItemCode,
                T1.Price AS PO_Price,
                T2.U_ListPrice AS Listed_Price
            FROM OPCH AS T0 
            INNER JOIN
            PCH1 AS T1 ON
            T0.DocEntry = T1.DocEntry
            LEFT OUTER JOIN    
            [dbo].[@PRICELISTS] AS T2 ON
            T1.ItemCode = T2.U_ItemNo
        WHERE
                    T1.DocEntry = @list_of_cols_val_tab_del) AND
            (T1.Price <> T2.U_ListPrice)   
    BEGIN
    SET @error = 123
    SET @error_message = 'Deviation in price'
    END
    END
    But after Execution got following Errors
    Msg 137, Level 15, State 2, Line 2
    Must declare the scalar variable "@transaction_type".
    Msg 137, Level 15, State 2, Line 19
    Must declare the scalar variable "@list_of_cols_val_tab_del".
    Msg 137, Level 15, State 1, Line 22
    Must declare the scalar variable "@error".
    Msg 137, Level 15, State 1, Line 23
    Must declare the scalar variable "@error_message".
    Please Help
    Regards
    Hitul

    Hi Hitul,
    Please check Snapshot.
    Please see Red Lines for SBO_SP_TransactionNotification Procedure.
    Paste your code below ADD YOUR CODE HERE.
    Hope this help
    Regards::::
    Atul Chakraborty

  • Must declare the Scalar variable *@prompt*.. (IES 10901)".

    Hi,
    I am getting an error: "Database error Must declare the Scalar variable *@prompt*.. (IES 10901)".
    backend: SQLServer
    The dim, Lovs are valid in IDT universe.
    There is a Fiscal Year Month Dim in Universe=SELECT
      cast(convert(varchar(6),DATEADD (YEAR,"COST_SUMMARY_FACT_VR"."FISC_YEAR"-1900,DATEADD(MONTH,"COST_SUMMARY_FACT_VR"."FISC_PERIOD"-1,DATEADD(DAY,0,0 ))),112) as int)
    FROM "COST_SUMMARY_FACT_VR"
    Lov
    There are two LOVs FP_From, FP_To
    1) FP_From= select distinct cast(convert(varchar(6),DATEADD (YEAR,"COST_SUMMARY_FACT_VR"."FISC_YEAR"-1900,DATEADD(MONTH,"COST_SUMMARY_FACT_VR"."FISC_PERIOD"-1,DATEADD(DAY,0,0 ))),112) as int) from COST_SUMMARY_FACT_VR order by 1
    2) FP_To=select distinct cast(convert(varchar(6),DATEADD (YEAR,"COST_SUMMARY_FACT_VR"."FISC_YEAR"-1900,DATEADD(MONTH,"COST_SUMMARY_FACT_VR"."FISC_PERIOD"-1,DATEADD(DAY,0,0 ))),112) as int) from COST_SUMMARY_FACT_VR order by 1
    Prompts
    There are two universe prompts
    1) FP_From is Numeric and LOV FP_From is attached
    2) FP_To is Numeric and LOV FP_To is attached
    Using the universe prompts in webi as
    Fiscal Year Month between FP_From and FP_To
    Qry is executing perfectly in backend.

    In addition to Visakh's solution: the reason you got the error message is because the piece of dynamic SQL is not part of the stored procedure, but constiutes a scope of its own. Thus variables declared in the surrounding procedure are not visible.
    Also, you should the dynamic SQL this way:
    SET @sql = N'
    SELECT @Result=COUNT( Id ) FROM  ' + quotename(@TableName) +
    ' WHERE RunRegisterKey=@ID'
    SET @Params = N'@Result int OUTPUT, @ID int'
    EXEC sys.sp_executesql @sql,@Params,@Result = @Result OUT, @ID = @ID
    That is, use quotename for the table name, in case you have a table named
    sys.objects; SHUTDOWN WITH NOWAIT; --
    Furthermore, pass @ID as a parameter rather than concatenating it to the string. It is both easier and safer.
    Erland Sommarskog, SQL Server MVP, [email protected]

  • Must declare the scalar variable

    I Am getting error as Must declare the scalar variable "@Imageid" for the following code,while executing,
    exec spGetPager  ' ' , ' ', ' 3 ', ' '
    In my coding I pass querystring value like 1,2,3 etc
    CREATE PROCEDURE spGetPager
          @PageNo int = 1,  
          @ItemsPerPage int = 1,  
     @Imageid int,
          @TotalRows int out  
    AS  
    BEGIN  
      SET NOCOUNT ON  
      DECLARE  
        @StartIdx int,  
        @SQL nvarchar(max),   
        @SQL_Conditions nvarchar(max),   
        @EndIdx int
          IF @PageNo < 1 SET @PageNo = 1  
          IF @ItemsPerPage < 1 SET @ItemsPerPage = 10  
          SET @StartIdx = (@PageNo -1) * @ItemsPerPage + 1  
          SET @EndIdx = (@StartIdx + @ItemsPerPage) - 1  
          SET @SQL = 'SELECT Imageid,Imagepath,imagename,username  
                    FROM (  
                    SELECT  ROW_NUMBER() OVER(ORDER BY Imageid) AS Row, *  
                          FROM  Imageupload ) AS tbl WHERE Imageid=@Imageid AND Row >= '  
                                        + CONVERT(varchar(9), @StartIdx) + ' AND  
                           Row <=  ' + CONVERT(varchar(9), @EndIdx)  
          EXEC sp_executesql @SQL  
          SET @SQL = 'SELECT @TotalRows=COUNT(*) FROM Imageupload'  
          EXEC sp_executesql  
            @query = @SQL,  
            @params = N'@TotalRows INT OUTPUT',  
            @TotalRows = @TotalRows OUTPUT  
    END
    Thanks in Advance

    you cant use variable directly in concatenation operator as its of type int. you need to cast it first as below
    CREATE PROCEDURE spGetPager
    @PageNo int = 1,
    @ItemsPerPage int = 1,
    @Imageid int,
    @TotalRows int out
    AS
    BEGIN
    SET NOCOUNT ON
    DECLARE
    @StartIdx int,
    @SQL nvarchar(max),
    @SQL_Conditions nvarchar(max),
    @EndIdx int
    IF @PageNo < 1 SET @PageNo = 1
    IF @ItemsPerPage < 1 SET @ItemsPerPage = 10
    SET @StartIdx = (@PageNo -1) * @ItemsPerPage + 1
    SET @EndIdx = (@StartIdx + @ItemsPerPage) - 1
    SET @SQL = 'SELECT Imageid,Imagepath,imagename,username
    FROM (
    SELECT ROW_NUMBER() OVER(ORDER BY Imageid) AS Row, *
    FROM Imageupload ) AS tbl WHERE Imageid=' + CAST(@Imageid AS varchar(50)) + ' AND Row >= '
    + CONVERT(varchar(9), @StartIdx) + ' AND
    Row <= ' + CONVERT(varchar(9), @EndIdx)
    EXEC sp_executesql @SQL
    SET @SQL = 'SELECT @TotalRows=COUNT(*) FROM Imageupload'
    EXEC sp_executesql
    @query = @SQL,
    @params = N'@TotalRows INT OUTPUT',
    @TotalRows = @TotalRows OUTPUT
    END
    That being I didnt understand why you need dynamic sql here. There's no dynamicity involved as i see
     you could simply use a sql like below
    CREATE PROCEDURE spGetPager
    @PageNo int = 1,
    @ItemsPerPage int = 1,
    @Imageid int,
    @TotalRows int out
    AS
    BEGIN
    SET NOCOUNT ON
    DECLARE
    @StartIdx int,
    @EndIdx int
    IF @PageNo < 1 SET @PageNo = 1
    IF @ItemsPerPage < 1 SET @ItemsPerPage = 10
    SET @StartIdx = (@PageNo -1) * @ItemsPerPage + 1
    SET @EndIdx = (@StartIdx + @ItemsPerPage) - 1
    SELECT Imageid,Imagepath,imagename,username
    FROM (
    SELECT ROW_NUMBER() OVER(ORDER BY Imageid) AS Row, *
    FROM Imageupload ) AS tbl WHERE Imageid=@Imageid
    AND Row >= @StartIdx
    AND Row <= @EndIdx
    SELECT @TotalRows=COUNT(*) FROM Imageupload
    END
    to achieve same requirement.
    Make sure you read
    http://www.sommarskog.se/dynamic_sql.html
    Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs

Maybe you are looking for

  • White Screen on MacBook Pro

    I have had moments where my mbp screen would "go black" for about 10 seconds, but they were intermittent, and it always came back up to where I was, with no error messages, etc. I am an old PC user, so I don't ever run more than three heavy duty prog

  • Adding new field in ME21N

    Hi, I want to add 5 new fileds in the header level  & item level of Me21N screen. The suggestion i have got is use <b>badi</b> <b>customer own screens in enjoy purchase order</b>. Please let me know the method to use for this badi or another way to a

  • Update rules infocube 0py_c02 not found BI 7.0

    Hello Forum, By activating the infocube standard payroll (0PY_C02), I found the problem that the rules for updating the infocube not exist and neither are activated in the BI content version 7.0. I have written a note to Sap, and I say it is not a mi

  • Need to apply a video filter to entire sequence...

    Hey gang- I'd really like to apply some filters (such as some color correctors and such) to an entire sequence. Same filter on all video. Copy and paste seems like a terrible waste of time, and short of exporting it and "flattening" it to it's own qu

  • Cancelling my subscription

    Hello, I'd like to cancel my subscription for Premiere Pro. Thank you.