SQL Max and Left functions

In a table I have a field "Ticket No.". I am using Ticket No in a format like:
00021-10-06-0201
The first set (left side) represents Ticket No. Then month, year, and code.
Each time when a user wants to enter new record a new ID is generated as:
"Select max(Left(TicketID,5)) from Ticket".
The new id becomes result+1.
I want to know that the above field is a string. But when I use LEFT
function, as above, it successfully returns max of the first set. Does
it automatically converts it to Long integer?
If not, how to use it securely so that first the left set is converted
to Long Integer and then the MAX is found. All in SQL query.

I want to know whether your "substr(00021...)
approach and in my example, does max function
automatically converts it to a numeric type.I did not use MAX in my example, but still it is converting to numeric depending on the operator you are using. Elaborating....see below..
SQL> select substr('00021-10-06-0021',1,5)+1 from dual;
SUBSTR('00021-10-06-0021',1,5)+1
                              22
SQL> select substr('A0021-10-06-0021',1,5)+1 from dual;
select substr('A0021-10-06-0021',1,5)+1 from dual
ERROR at line 1:
ORA-01722: invalid number
SQL> select substr('A0021-10-06-0021',1,5)||'A' from dual;
SUBSTR
A0021ASee the above 1st and 3rd query, the behaviour is completely based on the operators.

Similar Messages

  • Urgent(Right and Left Functions)

    Hello All,
    In our requiremnet it was mentioned like one column like right(columnname,13) and left(right(columnname,11),10).Is they are any functions like left and right in SQL?I didn't find any of these functions in SQL.
    Are they are something like Substr functions?
    Pls help me out.

    user631532 wrote:
    I mean it is something like right(columnname,13) means substr(columnname,-13)
    left(columnname,13) means substr(columnname,13)
    left(right(columnname,11),10) means substr(columnname,-11,10)
    right(left(columnname,11),10) means substr(columnname,11,-10).
    Is my understanding is correct?
    If not pls rply me.You could have read the documentation and tried it yourself...
    right 13
      1* select substr('0123456789ABCDEFGHIJKLM',-13) from dual
    SQL> /
    SUBSTR('01234
    ABCDEFGHIJKLMleft 13
      1* select substr('0123456789ABCDEFGHIJKLM',1,13) from dual
    SQL> /
    SUBSTR('01234
    0123456789ABCleft(right 11)10
      1* select substr('0123456789ABCDEFGHIJKLM',-11,10) from dual
    SQL> /
    SUBSTR('01
    CDEFGHIJKLright(left 11)10
      1* select substr(substr('0123456789ABCDEFGHIJKLM',1,11),-10) from dual
    SQL> /
    SUBSTR(SUB
    123456789A

  • SQL*Loader and DECODE function

    Hi All,
    I am loading data from data files into oracle tables and while loading the data using SQL*Loader, the following requirement needs to be fulfilled.
    1) If OQPR < 300, RB = $ 0-299, SC = "SC1"
    2) If 300 < OQPR < 1200, RB = $ 300-1199, SC = "SC2"
    3) If 1200 < OQPR < 3000, RB = $ 1200-2999, SC = "SC3"
    4) If OQPR > 3000 USD, RB = > $3000, SC = "SC4"
    Here OPQR is a field in the data file.
    Can anyone suggest how do we handle this using DECODE function? Triggers and PL/SQL functions are not to be used.
    TIA.
    Regards,
    Ravi.

    The following expression gives you different values for your different intervals and boundaries :
    SIGN(:OQPR - 300) + SIGN(:OQPR - 1200) + SIGN(:OQPR - 3000)

  • SQL Select and From Functions

    Can sql aggregate functions be added to an interface select clause and from clause.
    I want to have a datasource where one of the columns is an aggregate such as a count, which would need the ability to indicate a from clause function group by, or having by. In the Designer Diagram tab for the interface, it seems you can only apply sql functions to where clause joins or filters.
    I want to have a query such as follows as my datasource
    select columnA, count(*) as thecount
    from table x
    group by columnA
    order by thecount asc
    and ultimately
    select columnA, thecount
    from (select columnA, count(*) as thecount
    from table x
    group by columnA
    order by thecount asc)
    where rownum <1001
    Can this be done in the ODI Designer, without creating a physical custom view on the database?

    Hi lpantuso,
    Aggregate functions are added by ODI automatically. In this case you would want mappings like this:
    TARGET_COL_1: columnA
    TARGET_COL_2: count(*)
    ODI will generate something like this:
    select     
       columnA,
       count(*)
    from     MY_TABLE MY_TABLE
    where     
         (1=1)
    Group By MY_TABLE.columnA
    The subselect, however, isn't handled out of the box. In general ODI isn't quite as friendly with ordering clauses since order by is not relational. (Sets aren't ordered.) To get only the first 1000 columnA values, you'll probably need to create a view or break it into 2 separate interfaces.
    Regards,
    Matt

  • Min and Max and insert new rows

    Hello,
    I am really a beginner in Excel (2007). I am not sure if this is the correct forum, anyway.
    I have grouped some rows in a sheet (rows 1, 2 and 3, columns A and B, table below), some of the columns have numeric values in that group and I have a row (inside that group) that shows the maximum and minimum values (row 1):
              A     B 
    +  1   43   12 <- MAX and MIN values for row 2 and 3 columns A and B
    +  2   34   12
    +  3   43   34
    I am using MAX and MIN functions: A1 = MAX($A2:$A$3), B1 = MIN($B$2:$B$3)
    The problem comes when I want to insert more rows after row 3, the formula keeps wrapping to A$2:$A$3 therefore I need to readjust the formula to: MAX($A2:$A$4) manually (for MIN is the same).
              A     B 
    +  1   43   12 <- Are the same, they should be
    "98 and  10"
    +  2   34   12
    +  3   43   34
    +  4   98   10 <- New row, but the maximum and minimum continues to be the same, I want to extend the formula automatically to the 4 row when I insert the new row.
    Question:
    How can I extend the function of the MAX and MIN formula automatically when I insert new rows?
    Please consider that I may insert rows at the beginning, in the middle or the end.
    Thanks,
    Enrique.
    Kikeman Electric Systems Engineer

    Hi Enrique,
    Thanks for posting in MSDN.
    Based on the description, you want to modify the formula for the A1 and B1 cell when you insert a new rows.
    Yes, we can use Worksheet.Change to dermin the change of data on the worksheet then we can modify the formula as we wanted. Here is a sample for your reference:
    Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    Me.Range("A1").Formula = "=MAX($A2:$A" & Me.UsedRange.Rows.Count & ")"
    Me.Range("B1").Formula = "=MIN($B2:$B" & Me.UsedRange.Rows.Count & ")"
    End Sub
    You can more detail about Excel VBA developing from link below:
    Getting Started with VBA in Excel 2010
    Welcome to the Excel 2013 developer reference
    Regards & Fei
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • Moving max and moving minimum

    Hi,
    I'm trying to calculate moving max and minimum vales using odi. What is the best way of doing this, I'm thinking abt using oracle functions. Please let me know if there is any other way.
    Regards

    Hi Kumar,
    Thanks for the reply. In ODI version 10 are there any functions available to calculate moving max. I do see a max and min function under aggregate functions.
    Please let me know if you're talking abt these function. Thanks.
    Regards

  • Improve built in SQL MAX function

    Hi
    I am trying to improve the performance of the built in SQL max function. right now searching through over 500,000 rows takes lot of time which can be reduced. Can anyone suggest me something which would be helpful in this or may be give me a link if it has been discussed before?
    Anything is appreciated.
    Thanks

    Tolls wrote:
    Um...considering you were planning on improving on the MAX function, I sort of thought you might actually know how to use it. Otherwise how would you know it was running slowly?thanks Tolls i'd figured it out right after i posted it. i guess i was too excited after reading (you got it in milliseconds) that posted right away without doing anything myself..but yeah it did make it super fast..thanks a lot for your help and time..
    cotton.m wrote:
    d_khakh wrote:
    hi tolls thanks for getting back
    could u explain how did u do that? i found out how to create index..i have the following statement:
    create index col on table2 (col2);
    cud u tell me how to go from here and find the max in col2..thanks again for ur help?
    sigh
    Where to go from here? Just execute your damn query. If you really did create the index on the right column and your database isn't stupid and there isn't a lot more to this problem then you told us about like some where clauses then that's it. She's as fast as she's going to get.
    And remember, it's impolite to converse in a public forum while chewing your cud. Unless of course you actually meant "could" but were just too lazy to type it. Don't be lazy, use full words. Thanks.like i said above..i figured it out after some time.
    i wasn't being lazy ..thats msn talk..i thought people understood that..anyways your point noted too.

  • ODBC functions SQLExecDirectW and SQLExecute functions return error:"DIAG [22001] [Microsoft][SQL Server Native Client 10.0]String data, right truncation (0) "

    Problem Description:
    ODBC functions SQLExecDirectW and SQLExecute functions return error:”DIAG [22001] [Microsoft][SQL Server Native Client 10.0]String data, right
    truncation (0) “. When we enable tracing in the ODBC administrator, in the SQL.log we see that values for the arguments: ColumnSize, BufferLength, and StrLen_or_IndPtr of ODBC function SQLBindParameter are not being displayed.
    Environment Used:
    OS: Microsoft Windows Server 2003 R2 Standard x64 Edition.
    Complier: Microsoft Visual Studio 2008 SP1 for x64.
    Database: Microsoft SQL Server 2008
    MDAC: Microsoft Data Access Components SDK 2.8
    Note: This problem is seen only in our 64bit application. However, in 32bit
    SQLExecDirectW and SQLExecute functions return successfully.
    As we could not find the values of 6<sup>th</sup>, 9<sup>th</sup> and 10<sup>th</sup> arguments(ColumnSize,
    BufferLength, and StrLen_or_IndPtr) passed to
    SQLBindParameter in the ODBC traces for 64bit, we are not sure whether the values for the above mentioned arguments are received correctly by SQLBindParameter or not. This information would help us to debug further. So, could you please let us know why
    these values are not displayed.
    1)Here is the extract of the SQL.log file for 32bit where the values for SQLULEN , SQLLEN and SQLLEN* are displayed properly:
    PR0CNFG 1028-15f0 ENTER SQLBindParameter
    HSTMT 0x006FBDD8
    UWORD 1
    SWORD 1 <SQL_PARAM_INPUT>
    SWORD -8 <SQL_C_WCHAR>
    SWORD -9 <SQL_WVARCHAR>
    SQLULEN 23
    SWORD 0
    PTR 0x0595EBBA
    SQLLEN 46
    SQLLEN * 0x05A5FB00
    2)Here is the extract of the SQL.log file for 64bit where the values for SQLULEN , SQLLEN are not displayed properly and
    SQLExecDirectW function return error:”DIAG
    [22001] [Microsoft][SQL Server Native Client 10.0]String data, right truncation (0) “. :
    PR0CNFG a78-fe4 ENTER SQLBindParameter
    HSTMT 000000000431D2F0
    UWORD 1
    SWORD 1 <SQL_PARAM_INPUT>
    SWORD -8 <SQL_C_WCHAR>
    SWORD -9 <SQL_WVARCHAR>
    SQLULEN SQLULEN SWORD 0
    PTR 0x0000000005364EFA
    SQLLEN SQLLEN
    SQLLEN * SQLLEN *
    PR0CNFG a78-fe4 EXIT SQLBindParameter with return code 0 (SQL_SUCCESS)
    HSTMT 000000000431D2F0
    UWORD 1
    SWORD 1 <SQL_PARAM_INPUT>
    SWORD -8 <SQL_C_WCHAR>
    SWORD -9 <SQL_WVARCHAR>
    SQLULEN SQLULEN SWORD 0
    PTR 0x0000000005364EFA
    SQLLEN SQLLEN SQLLEN *

    Hi Nalsr,
    From my research, I found:
    "[Microsoft][ODBC SQL Server Driver]String
    data right truncation" error may be returned from a call to
    SQLBindParameter if the size of the string parameter being used is greater than the size of the column being compared to. In other words if the
    string size of the <expression> to the left of the <comparison_operator> is less than the
    string size of the <expression> to the
    right, ODBC may return this error.
    The resolution is to make the string size of the <expression> to the
    right of the <comparison_operator> less than or equal to the
    string size of the <expression> on the left.
    It is difficult to track down this type of problem when third party development applications are being used. ODBC Trace can be used to help determine if this problem is occuring.
    Here is an example where the customer has submitted a query "select count(*) from type1 where type1 = ?", type1 is varchar(5) and the
    data type being passed by the application is char[9].
    Here is the relevant portion of the trace. The following information from the "exit" of SQLDescribeParam
    SWORD * 0x0095e898 (12)
    UDWORD * 0x0095e880 (5)
    Maps to the following with the actual value in parenthesis - SQL_VARCHAR Size 5:
    SQLSMALLINT *DataTypePtr
    SQLUINTEGER *ParameterSizePtr
    The "exit" value from SQLBindParameter provides the following
    information:
    SWORD 1 <SQL_PARAM_INPUT>
    SWORD 1 <SQL_C_CHAR>
    SQL Data Type SWORD 12 <SQL_VARCHAR>
    Parameter Size UDWORD 5
    SWORD 0
    Value PTR 0x0181c188
    Value Buffer Size SDWORD 5
    String Length SDWORD * 0x0181c103 (9)
    The string length parameter is the length of the
    string being bound to the parameter, in this instance there is a size mismatch which results in the SQLError and the SQLErrorW with the message "[Microsoft][ODBC SQL Server
    Driver]String data
    right truncation" .
    Hope this could be helpful.
    Best regards,
    Halin Huang

  • How to write SQL query and apply aggregate functions on it

    Hello experts,
    Iu2019ve a task to write SQL query on tree tables and do inner join on them. Iu2019ve accomplish this task by using T-CODE SQVI. However now I need to write a query and apply SQL functions on it i.e. Add, Count, Max and Min etc. Please can someone tell me how I can write SQL query with aggregate functions in SAP?
    Thanks a lot in advance

    HI Mr. Cool
    you can see the below code for using aggregate functions.
    where ARTIST and SEATSOCCU are the field names for which you want to perform these functions.
    DATA: TOTAL_ENTRIES TYPE I,
          TOTAL_ATT TYPE I,
          MAX_ATT TYPE I,
          AVG_ATT TYPE I.
    SELECT COUNT( DISTINCT ARTIST )
           SUM( SEATSOCCU )
           MAX( SEATSOCCU )
           AVG( SEATSOCCU ) FROM YCONCERT INTO (TOTAL_ENTRIES, TOTAL_ATT,
    MAX_ATT, AVG_ATT).
    Thanks
    Lalit Gupta

  • Since installing LTR 5.4, which I've now upgraded to 5.6, I've encountered repeated slowness and malfunctions in operations, especially when using the Compare View function and the Tab key to open and close the right and left side panels.  Such problems n

    Since installing LTR 5.4, which I've now upgraded to 5.6, I've encountered repeated slowness and malfunctions in operations, especially when using the Compare View function and the Tab key to open and close the right and left side panels.  Such problems never arose during two years of using LTR-4 and nothing else has changed on my computer.  I have a pretty simple system with only a few plug-ins, which are usually not in operation.  I have 12GB of RAM in my Windows 7 PC.  I could illustrate these problems with screen shots if you would tell me how to submit screen shots.  Otherwise I will try to describe the problems in words.
    The problem is clearly cumulative, growing worse as usage time passes.  Compare View feature gradually slows down and eventually seems to choke as my work session proceeds. If I Exit LTR and re-enter and start all over, things will work normally for maybe 30 minutes, but then the Compare View feature begins to become very slow to respond.   In a recent example with my screen full of thumbnails in Library mode I highlighted two images to compare. LTR started to open the Compare View screen by first having the top row of thumbnails disappear to be replaced by the "SELECT" and "CANDIDATE" words in their spaces  (but no images), but Compare View never succeeded in gaining control of the screen. After some seconds the top row of thumbnails reasserted its position and the Compare View windows disappeared. But LTR kept trying to bring them back. Again the top row of thumbnails would go away, Select and candidate would reappear, try again, and give up. This went on for at least 2-3 minutes before I tried to choose File and Exit, but even that did not initially want to respond. It doesn't like to accept other commands when it's trying to open Compare View. Finally it allowed me to exit.
    To experiment I created a new catalog of 1100 images.  After 30-40 minutes, the Compare View function began to operate very slowly. With left and right side panels visible and two thumbnails highlighted, hitting Compare View can take half a minute before the two mid-size  images open in their respective SELECT and CANDIDATE windows. When the side panels are open and two images are in the Select/Candidate spaces, hitting the Tab button to close the side panels produces a very delayed response--25-30 seconds to close them, a few more seconds to enlarge the two images to full size. To reverse the process (i.e., to recall the two side panels), hitting Tab would make the two sides of the screen go black for up to a minute, with no words visible. Eventually the info fields in the panels would open up.
    I also created a new user account and imported a folder of 160 images. After half an hour Compare View began mis-placing data.  (I have a screen shot to show this.)  CANDIDATE appears on the left side of SELECT, whereas it should be on the right. The accompanying camera exposure data appears almost entirely to the left of the mid-screen dividing line. Although the Candidate and Select headings were transposed, the image exposure data was not, but the data for the image on the right was almost entirely to the left of the line dividing the screen in two.
    Gurus in The Lightroom Forum have examined Task Manager data showing Processes running and Performance indicators and they see nothing wrong.  I could also send screen shots of this data.
    At this point, the only way I can process my images is to work 30-40 minutes and then shut down everything, exit, and re-start LTR.  This is not normal.  I hope you can find the cause, and then the solution.  If you would like to see my screen shots, tell me how to submit them.
    Ollie
    [email protected]

    Since installing LTR 5.4, which I've now upgraded to 5.6, I've encountered repeated slowness and malfunctions in operations, especially when using the Compare View function and the Tab key to open and close the right and left side panels.  Such problems never arose during two years of using LTR-4 and nothing else has changed on my computer.  I have a pretty simple system with only a few plug-ins, which are usually not in operation.  I have 12GB of RAM in my Windows 7 PC.  I could illustrate these problems with screen shots if you would tell me how to submit screen shots.  Otherwise I will try to describe the problems in words.
    The problem is clearly cumulative, growing worse as usage time passes.  Compare View feature gradually slows down and eventually seems to choke as my work session proceeds. If I Exit LTR and re-enter and start all over, things will work normally for maybe 30 minutes, but then the Compare View feature begins to become very slow to respond.   In a recent example with my screen full of thumbnails in Library mode I highlighted two images to compare. LTR started to open the Compare View screen by first having the top row of thumbnails disappear to be replaced by the "SELECT" and "CANDIDATE" words in their spaces  (but no images), but Compare View never succeeded in gaining control of the screen. After some seconds the top row of thumbnails reasserted its position and the Compare View windows disappeared. But LTR kept trying to bring them back. Again the top row of thumbnails would go away, Select and candidate would reappear, try again, and give up. This went on for at least 2-3 minutes before I tried to choose File and Exit, but even that did not initially want to respond. It doesn't like to accept other commands when it's trying to open Compare View. Finally it allowed me to exit.
    To experiment I created a new catalog of 1100 images.  After 30-40 minutes, the Compare View function began to operate very slowly. With left and right side panels visible and two thumbnails highlighted, hitting Compare View can take half a minute before the two mid-size  images open in their respective SELECT and CANDIDATE windows. When the side panels are open and two images are in the Select/Candidate spaces, hitting the Tab button to close the side panels produces a very delayed response--25-30 seconds to close them, a few more seconds to enlarge the two images to full size. To reverse the process (i.e., to recall the two side panels), hitting Tab would make the two sides of the screen go black for up to a minute, with no words visible. Eventually the info fields in the panels would open up.
    I also created a new user account and imported a folder of 160 images. After half an hour Compare View began mis-placing data.  (I have a screen shot to show this.)  CANDIDATE appears on the left side of SELECT, whereas it should be on the right. The accompanying camera exposure data appears almost entirely to the left of the mid-screen dividing line. Although the Candidate and Select headings were transposed, the image exposure data was not, but the data for the image on the right was almost entirely to the left of the line dividing the screen in two.
    Gurus in The Lightroom Forum have examined Task Manager data showing Processes running and Performance indicators and they see nothing wrong.  I could also send screen shots of this data.
    At this point, the only way I can process my images is to work 30-40 minutes and then shut down everything, exit, and re-start LTR.  This is not normal.  I hope you can find the cause, and then the solution.  If you would like to see my screen shots, tell me how to submit them.
    Ollie
    [email protected]

  • SQL 2012 and later will fail to publish a database for any tables with a default constraint that references a user defined function.

    Script will create database, 3 database objects and publish. 
    The error is due to the generation script to create the conflict tables that is not stripping out default constraints that reference a UDF. 
    As you can see below, the failure is on the generation script for the conflict table.
    The conflict table should be a bucket table that shouldn’t enforce data integrity. 
    See how the default constraints for the columns someint and somestring were stripped out of the generation logic however the default constraint that utilizes a UDF persist and uses the same object name that was used on the production table (The
    bold line) , this occurs if I explicitly name the constraint or let the system generate the name for me like in the example posted. 
      The only way I could see getting around this right now is to drop all default constraints in the system that uses a UDF, publish then add the constraints back which is vulnerable to invalid data and a lot of moving
    steps.  This all worked with SQL 2000, 2005, 2008, 2008r2, it’s stopped working in SQL 2012 and continues to not work in SQL 2014. 
    Error messages:
    Message: There is already an object named 'DF__repTable__id__117F9D94' in the database.
    Could not create constraint. See previous errors.
    Command Text: CREATE TABLE [dbo].[MSmerge_conflict_MergeRepFailurePublication_repTable](
            [id] [varchar](8) NULL CONSTRAINT [DF__repTable__id__117F9D94]  DEFAULT ([dbo].[repUDF]()),
            [somedata] [varchar](64) NULL,
            [rowguid] [uniqueidentifier] ROWGUIDCOL  NULL,
            [someint] [int] NULL,
            [somestring] [varchar](64) NULL
    Parameters:
    Stack:    at Microsoft.SqlServer.Replication.AgentCore.ReMapSqlException(SqlException e, SqlCommand command)
       at Microsoft.SqlServer.Replication.AgentCore.AgentExecuteNonQuery(SqlCommand command, Int32 queryTimeout)
       at Microsoft.SqlServer.Replication.AgentCore.ExecuteDiscardResults(CommandSetupDelegate commandSetupDelegate, Int32 queryTimeout)
       at Microsoft.SqlServer.Replication.Snapshot.YukonMergeConflictTableScriptingManager.ApplyBaseConflictTableScriptToPublisherIfNeeded(String strConflictScriptPath)
       at Microsoft.SqlServer.Replication.Snapshot.BaseMergeConflictTableScriptingManager.DoConflictTableScriptingTransaction(SqlConnection connection)
       at Microsoft.SqlServer.Replication.RetryableSqlServerTransactionManager.ExecuteTransaction(Boolean bLeaveTransactionOpen)
       at Microsoft.SqlServer.Replication.Snapshot.BaseMergeConflictTableScriptingManager.DoConflictTableScripting()
       at Microsoft.SqlServer.Replication.Snapshot.MergeSmoScriptingManager.GenerateTableArticleCftScript(Scripter scripter, BaseArticleWrapper articleWrapper, Table smoTable)
       at Microsoft.SqlServer.Replication.Snapshot.MergeSmoScriptingManager.GenerateTableArticleScripts(ArticleScriptingBundle articleScriptingBundle)
       at Microsoft.SqlServer.Replication.Snapshot.MergeSmoScriptingManager.GenerateArticleScripts(ArticleScriptingBundle articleScriptingBundle)
       at Microsoft.SqlServer.Replication.Snapshot.SmoScriptingManager.GenerateObjectScripts(ArticleScriptingBundle articleScriptingBundle)
       at Microsoft.SqlServer.Replication.Snapshot.SmoScriptingManager.DoScripting()
       at Microsoft.SqlServer.Replication.Snapshot.SqlServerSnapshotProvider.DoScripting()
       at Microsoft.SqlServer.Replication.Snapshot.MergeSnapshotProvider.DoScripting()
       at Microsoft.SqlServer.Replication.Snapshot.SqlServerSnapshotProvider.GenerateSnapshot()
       at Microsoft.SqlServer.Replication.SnapshotGenerationAgent.InternalRun()
       at Microsoft.SqlServer.Replication.AgentCore.Run() (Source: MSSQLServer, Error number: 2714)
    Get help: http://help/2714
    Server COL-PCANINOW540\SQL2012, Level 16, State 0, Procedure , Line 1
    Could not create constraint. See previous errors. (Source: MSSQLServer, Error number: 1750)
    Get help: http://help/1750
    Server COL-PCANINOW540\SQL2012, Level 16, State 0, Procedure , Line 1
    Could not create constraint. See previous errors. (Source: MSSQLServer, Error number: 1750)
    Get help: http://help/1750
    Pauly C
    USE [master]
    GO
    CREATE DATABASE [MergeRepFailure]
    ALTER DATABASE [MergeRepFailure] SET COMPATIBILITY_LEVEL = 110
    GO
    USE [MergeRepFailure]
    GO
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    create view
    [dbo].[repView] as select right(newid(),8) as id
    GO
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    CREATE FUNCTION [dbo].[repUDF]()
    RETURNS varchar(8)
    BEGIN
    declare @val varchar(8)
    select top 1 @val = id from [repView]
    return @val
    END
    GO
    create table repTable
    id varchar(8) default([dbo].[repUDF]()),
    somedata varchar(64) null,
    rowguid uniqueidentifier ROWGUIDCOL default(newid()),
    someint int default(1),
    somestring varchar(64) default('somestringvalue')
    GO
    insert into reptable (somedata) values ('whatever1')
    insert into reptable (somedata) values ('whatever2')
    go
    /*test to make sure function is working*/
    select * from reptable
    GO
    /*Publish database*/
    use [MergeRepFailure]
    exec sp_replicationdboption @dbname = N'MergeRepFailure', @optname = N'merge publish', @value = N'true'
    GO
    declare @Descrip nvarchar(128)
    select @Descrip = 'Merge publication of database ''MergeRepFailure'' from Publisher ''' + @@servername +'''.'
    print @Descrip
    -- Adding the merge publication
    use [MergeRepFailure]
    exec sp_addmergepublication @publication = N'MergeRepFailurePublication', @description = N'@Descrip',
    @sync_mode = N'native', @retention = 14, @allow_push = N'true', @allow_pull = N'true', @allow_anonymous = N'true',
    @enabled_for_internet = N'false', @snapshot_in_defaultfolder = N'true', @compress_snapshot = N'false', @ftp_port = 21,
    @ftp_subdirectory = N'ftp', @ftp_login = N'anonymous', @allow_subscription_copy = N'false', @add_to_active_directory = N'false',
    @dynamic_filters = N'false', @conflict_retention = 14, @keep_partition_changes = N'false', @allow_synctoalternate = N'false',
    @max_concurrent_merge = 0, @max_concurrent_dynamic_snapshots = 0, @use_partition_groups = null, @publication_compatibility_level = N'100RTM',
    @replicate_ddl = 1, @allow_subscriber_initiated_snapshot = N'false', @allow_web_synchronization = N'false', @allow_partition_realignment = N'true',
    @retention_period_unit = N'days', @conflict_logging = N'both', @automatic_reinitialization_policy = 0
    GO
    exec sp_addpublication_snapshot @publication = N'MergeRepFailurePublication', @frequency_type = 4, @frequency_interval = 14, @frequency_relative_interval = 1,
    @frequency_recurrence_factor = 0, @frequency_subday = 1, @frequency_subday_interval = 5, @active_start_time_of_day = 500, @active_end_time_of_day = 235959,
    @active_start_date = 0, @active_end_date = 0, @job_login = null, @job_password = null, @publisher_security_mode = 1
    use [MergeRepFailure]
    exec sp_addmergearticle @publication = N'MergeRepFailurePublication', @article = N'repTable', @source_owner = N'dbo', @source_object = N'repTable', @type = N'table',
    @description = null, @creation_script = null, @pre_creation_cmd = N'drop', @schema_option = 0x000000010C034FD1, @identityrangemanagementoption = N'manual',
    @destination_owner = N'dbo', @force_reinit_subscription = 1, @column_tracking = N'false', @subset_filterclause = null, @vertical_partition = N'false',
    @verify_resolver_signature = 1, @allow_interactive_resolver = N'false', @fast_multicol_updateproc = N'true', @check_permissions = 0, @subscriber_upload_options = 0,
    @delete_tracking = N'true', @compensate_for_errors = N'false', @stream_blob_columns = N'false', @partition_options = 0
    GO
    use [MergeRepFailure]
    exec sp_addmergearticle @publication = N'MergeRepFailurePublication', @article = N'repView', @source_owner = N'dbo', @source_object = N'repView',
    @type = N'view schema only', @description = null, @creation_script = null, @pre_creation_cmd = N'drop', @schema_option = 0x0000000008000001,
    @destination_owner = N'dbo', @destination_object = N'repView', @force_reinit_subscription = 1
    GO
    use [MergeRepFailure]
    exec sp_addmergearticle @publication = N'MergeRepFailurePublication', @article = N'repUDF', @source_owner = N'dbo', @source_object = N'repUDF',
    @type = N'func schema only', @description = null, @creation_script = null, @pre_creation_cmd = N'drop', @schema_option = 0x0000000008000001,
    @destination_owner = N'dbo', @destination_object = N'repUDF', @force_reinit_subscription = 1
    GO

    More information, after running a profile trace the following 2 statements, the column with the default on a UDF returns a row while the other default does not.  This might be the cause of this bug.  Is the same logic to generate the object on
    the subscriber used to generate the conflict table?  
    exec sp_executesql N'
    select so.name, schema_name(so.schema_id)
    from sys.sql_dependencies d
    inner join sys.objects so
    on d.referenced_major_id = so.object_id
    where so.type in (''FN'', ''FS'', ''FT'', ''TF'', ''IF'')
    and d.class in (0,1)
    and d.referenced_major_id <> object_id(@base_table, ''U'')
    and d.object_id = object_id(@constraint, ''D'')',N'@base_table nvarchar(517),@constraint nvarchar(517)',@base_table=N'[dbo].[repTable]',@constraint=N'[dbo].[DF__repTable__id__117F9D94]'
    exec sp_executesql N'
    select so.name, schema_name(so.schema_id)
    from sys.sql_dependencies d
    inner join sys.objects so
    on d.referenced_major_id = so.object_id
    where so.type in (''FN'', ''FS'', ''FT'', ''TF'', ''IF'')
    and d.class in (0,1)
    and d.referenced_major_id <> object_id(@base_table, ''U'')
    and d.object_id = object_id(@constraint, ''D'')',N'@base_table nvarchar(517),@constraint nvarchar(517)',@base_table=N'[dbo].[repTable]',@constraint=N'[dbo].[DF__repTable__somein__1367E606]'
    Pauly C

  • Any difference between distinct and aggregate function in sql query cost???

    Hi,
    I have executed many sql stmts patterns- such as:
    a) using a single table
    b) using two tables, using simple joins or outer joins
    but i have not noticed any difference in sql stmts in cost and in execution plan....
    Anyway, my colleague insists on that using aggregate function is less costly compared to
    distinct....(something i have not confirmed, that's why i beleive that they are exactly the same...)
    For the above reffered 1st sql pattern.. we could for example use
    select distinct deptno
    from emp
    select count(*), deptno
    from emp
    group by deptno select distinct owner, object_type from all_objects
    select count(*), owner, object_type from all_objects
    group by owner, object_typeHave you found any difference between the two ever...????
    Note: I use Ora DB 10g v2.
    Thank you,
    Sim

    distinct and aggregate function are for different uses and may give same result but if u r using aggregate function to get distinct records, it will be expensive...
    ex
    select distinct deptno from scott.dept;
    Statistics
    0 recursive calls
    0 db block gets
    2 consistent gets
    0 physical reads
    0 redo size
    584 bytes sent via SQL*Net to client
    488 bytes received via SQL*Net from client
    2 SQL*Net roundtrips to/from client
    0 sorts (memory)
    0 sorts (disk)
    4 rows processed
    select deptno from scott.emp group by deptno;
    Statistics
    307 recursive calls
    0 db block gets
    60 consistent gets
    6 physical reads
    0 redo size
    576 bytes sent via SQL*Net to client
    488 bytes received via SQL*Net from client
    2 SQL*Net roundtrips to/from client
    6 sorts (memory)
    0 sorts (disk)
    3 rows processed
    Nimish Garg
    Software Developer
    *(Oracle & ASP.NET)*
    Indiamart Intermesh Limited, Noida
    To Get Free Oracle & ASP.NET Code Snippets
    Follow: http://nimishgarg.blogspot.com

  • Are the Pl/sql procedure and function atomic by themself

    i want to ask a question does oracle pl/sql procedure and function support Atomicity for the database by themself , or they became atomic incase we call them using begin -- end;

    You appear to be discussing transaction scope which is completely independent of PL/SQL blocks like procedures or how you call procedures. It's all in where commits (or rollbacks) are issued.
    If you have a procedure like this
    CREATE PROCEDURE p1
    AS
    BEGIN
      INSERT INTO some_table( key, value ) VALUES( 1, 'Foo' );
      INSERT INTO some_table( key, value ) VALUES( 1, 'Bar' );
    END;where the first statement succeeds and the second statement fails as a result of a duplicate key, there will still be a Foo row in the table but the procedure will have thrown an exception. The caller of the procedure may choose to commit or rollback the change-- that will determine whether the first statement's results are made permanent. If you have a procedure like this,
    CREATE PROCEDURE p1
    AS
    BEGIN
      INSERT INTO some_table( key, value ) VALUES( 1, 'Foo' );
      commit;
      INSERT INTO some_table( key, value ) VALUES( 1, 'Bar' );
    END;the commit will make the first insert permanent regardless of whether the second statement fails no matter what the calling code does (that's one reason that putting commits in stored procedures is generally a bad idea-- the caller is in a much better position to know what other uncommitted work has been done and whether it is safe to commit.
    Justin

  • Problem with DBMS_OUTPUT and SQL statment with a function

    I am using SQL Developer version 3.0.04 and I have a function that has a dbms_output statment in it. I am running the following SQL to select the output of that statment.
    select A.A_FUCTION('TEST') from dual;
    The output works fine but the dbms_output line does not show in the dbms_output window. I turned on the output window etc. and i can get the select to print out the output if i wrap it in a declare begin end wrapper... and then change the query to insert the return value into variable.
    just wondering if there is way to get the dbms_output to flush out with just an SQL statment instead of in a begin end wrapper etc.

    just wondering if there is way to get the dbms_output to flush out with just an SQL statment instead of in a begin end wrapper etc.works fine in sql*plus, so I guess it must be a preference or sth. in sql*developer:
    SQL> set serverout on
    SQL> create or replace function f1 (r int)
      2    return int
      3  as
      4  begin
      5    dbms_output.put_line ('Hello World ' || r);
      6    return r;
      7  end f1;
      8  /
    Function created.
    SQL>
    SQL> select f1 (rownum) f1 from dual connect by level <= 3
      2  /
            F1
             1
             2
             3
    3 rows selected.
    Hello World 1
    Hello World 2
    Hello World 3
    SQL>

  • SQL Loader : Trim and Decode functions help please

    Hi,
    I have to load data from a flat file, for some columns i need to use TRIM and DECODE functions.It is a pipe delimited file.
    I get syntax errors (one is below) same error listed for TRIM.
    SQL*Loader-350: Syntax error at line xx.
    Expecting "," or ")", found "DECODE".
    ===========
    ,FINAL_BILL_DATE CHAR(30) "TRIM(:FINAL_BILL_DATE)"
    ,BUSINESS_ID "DECODE(:BUSINESS_ID,'B',1,'C',2,'E',3,'G',4,'O',5,'R',6,'T',7,'U',8,'H',9,-1)"
    Can anyone please help.
    Thanks
    Cherrish

    Hello Cherrish.
    The error you are receiving leads me to believe that at some point prior to the DECODE on the line for BUSINESS_ID, probably some line even before the FINAL_BILL_DATE line, there a syntactical error causing the quotes before the DECODE to actually terminate some other syntax. Without all of the lines that could actually contribute to this, including the header details, this is the best I can advise.
    Hope this helps,
    Luke
    Please mark the answer as helpful or answered if it is so. If not, provide additional details.
    Always try to provide create table and insert table statements to help the forum members help you better.

Maybe you are looking for

  • Transferring Mail using Target Disc Mode

    Please I am begging for someone to help me ! I have an older Macbook Pro , that is running , or was running Mavericks 10.9.2. Awhile ago it quit booting and  a reinstal using recovery was unsuccessful.  Using disk utility i was able to determine the

  • MoveUser command in Verson 6.3 is weird 1

    Hi everyone. ^^ I have one question about "MoveUser" command in mail server version 6.3. I upgraded one of my store server to version 6.3. When I moved users from version 6.3 to 5.2 with 6.3 MoveUser command, it didn't work. but reverse case (5.2 to

  • Is it possible to delete a folder from my Time Machine backups?

    Hi. I have Time Machine running on my office computer. It has backed up all my data since September. Problem is that I need to delete a folder from the backups that contains personal work. Is it possible to delete 1 folder from all the backups? If no

  • KDEmod hangs when logging out, rebooting etc

    Hello I just did a reinstall of Arch, and decided to try KDEmod for the first time.  Unfortunately when I try logging out, or rebooting, all that happens is that I get a black screen with a cursor and then it just hangs like that.  Does anyone know w

  • Expain code

    hi all, can anyone explain wht does this code mean? column xdb_name new_value xdb noprint; select name||': ' xdb_name from v$database;