Max Of SQL

on 11G
I have a simple problem, but for some reason, probably been doing too many things today, it is not working... here is some sample data on 1 customer_id that is a duplicate and I need Max of to pick 1 row - on the most recent Date.
customer_id number
store number
date varchar2(100) represents MMYYYY (Month/Year)
111123432         111         042011
111123432         234         112010So I transpose that in my SQL so that it comes out as YYYYMM, since the TO_DATE field wants more data and I don't know that or fully understand how to use this, clients just wants it fast and dirty, so that's what I am planning to do.
The query that I need is to pick 1 row for the duplicate, based on the Date field, the most recent Date [please no smart remarks that I should convert that to a Real Date, client WANTS it like that!!! and they pay the bills $$$ :- ) ] they do not want a real date field.
so I though that this would be simple:
select customer_id, store, MAX (SUBSTR(DATE,3,4) || SUBSTR(DATE,1,2) ) as YYYYDD
from Table
where cust_id=111123432
Group by cust_id, store;
I end up with the 2 rows, and not the 1 that I need.
What am I doing wrong ?

Kodiak_Seattle wrote:
on 11G
I have a simple problem, but for some reason, probably been doing too many things today, it is not working... here is some sample data on 1 customer_id that is a duplicate and I need Max of to pick 1 row - on the most recent Date.
customer_id number
store number
date varchar2(100) represents MMYYYY (Month/Year)
111123432         111         042011
111123432         234         112010So I transpose that in my SQL so that it comes out as YYYYMM, since the TO_DATE field wants more data and I don't know that or fully understand how to use this, clients just wants it fast and dirty, so that's what I am planning to do.
The query that I need is to pick 1 row for the duplicate, based on the Date field, the most recent Date [please no smart remarks that I should convert that to a Real Date, client WANTS it like that!!! and they pay the bills $$$ :- ) ] they do not want a real date field.
so I though that this would be simple:
select customer_id, store, MAX (SUBSTR(DATE,3,4) || SUBSTR(DATE,1,2) ) as YYYYDD
from Table
where cust_id=111123432
Group by cust_id, store;
I end up with the 2 rows, and not the 1 that I need.
What am I doing wrong ?MAX() function need to be in WHERE clause

Similar Messages

  • Nvarchar(max) of sql server 2005 is not accessible through Oracle DB Link

    hi,
    i have created the DB LINK from Oralce 11gR2 to MS Sql Server 2005,
    am able to access the view of Sql Server from Oralce,
    but the Columns which have Datatype nvarchar(max) in Sql Server am not able to access through DB Link.
    can anybody know about this issues?

    Pl do not post duplicate threads - Datatype nvarchar(max) not accessable (DB Link from Sql 2005 to Ora 11gR2 )

  • SQL MAX QUERY / SQL COUNT QUERY

    Hi all,
    i would like to get the value of the number of rows i have, but i dun seem to work it out with the getRow statements. i think the syntax of my statement is ok, but maybe i am doing the wrong way to get the value out.
    I tried with COUNT, and it gives me the same error.
    The error is: java.sql.SQLException: Column not found
    This is the part of my code
    Connection con;
    String Q;
    try{
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    con = DriverManager.getConnection("jdbc:odbc:RFID Logistics");
    Statement stmt = con.createStatement();
    ResultSet rs = stmt.executeQuery("SELECT MAX(Queue) FROM Forklift1");
    while(rs.next())
                        Q = rs.getString("Queue");
                        System.out.println(Q);
              catch(ClassNotFoundException f)
                   f.printStackTrace();
              catch(SQLException f)
                   f.printStackTrace();
    Thx alot in advance =)

    Please use code tags when posting code. There is a code button above the message editor that inserts the tags.
    Do you want to get the number of rows? If soConnection con;
    int num = 0;
    try{
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    con = DriverManager.getConnection("jdbc:odbc:RFID Logistics");
    Statement stmt = con.createStatement();
    ResultSet rs = stmt.executeQuery("SELECT COUNT(*) FROM Forklift1");
    while(rs.next())
    num = rs.getInt(1);
    System.out.println(num );
    rs.close();
    stmt.close();
    catch(ClassNotFoundException f)
    f.printStackTrace();
    catch(SQLException f)
    f.printStackTrace();
    }This is untested, but should be close enough.

  • B1 create User Defined Field as nvarchar(max) in SQL 2005 database

    Hi everyone,
    I just created a UDF in B1 as alphanumeric(12), and noticed that B1 created a field in SQL 2005 as nvarchar(max) instead of nvarchar(12). I tested with both 2005A SP01 patch 14 and patch 20. It always creates UDF as nvarchar(max). Is this a bug? It will cause db file use more disk space and also reduce the query performance. Also, B1 won't create the index on the UDF even if you select the option.
    Thanks for help,
    David

    Hi David,
    I was running on patch 19 when I wrote my earlier posts. I'm now running patch 20 without any issues. I also have a range of clients who are running SBO 2005A SP1 on various patch levels above 10 (though not all are on SQL 2005) and I've yet to come across this issue.
    Did you log this with SAP Support? Have they come up with any suggestions?
    Maybe this will work:
    1) Start SBO. When you get to the login screen, click on Choose Company.
    2) Change the Current Server field from SQL 2005 to SQL 2000. Reenter your server settings if prompted
    3) Login as normal and try and create your field.
    4) Log out and go back in to change back to SQL 2005
    Kind Regards,
    Owen

  • Max of Sql query

    CREATE TABLE [dbo].[S_Products] (
    [Serial] [varchar] (15) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    [ItemCode] [varchar] (10) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
    [Qty] [float] NULL 
    // here serialno is unique but itemcode will occure 1 more times. 
    Sample Date 
    Serial       Itemcode  Qty
    20135091 00551002 16.0
    20135114 00551003 11.0
    20135075 00551003 11.0
    20135129 00551005 
    4.0
    20135103 00551005 
    2.0
    I want to get serial numnber ,qty corresponding to max of Qty which
    is > 0
    plz give me the query for it. Plz note that my serial number is unique
    , but item code is multiple. So i one item code and qty and corresponding serial which is max(qty) > 0 
    AK

    I want serial,qty,Itemcode  which is corresponding to max(qty) for multiple same itemcode
    erial       Itemcode  Qty
    20135091 00551002 16.0
    20135114 00551003 11.0
     <=
     ItemCode Repeated    . So 11.o qty is max so any of these
    20135075 00551003 11.0
      <=
     ItemCode Repeated    . So 11.o qty is max so any
    of these
    20135129 00551005 4.0
        <=  ItemCode Repeated    . So 4.o qty is max so I need this record
    20135103 00551005 2.0
         <=  ItemCode Repeated  No nedd this record , bcz qty less
    AK

  • Greatest and Max in sql

    greatest means it take the high value frm the exprn,,,,isnt it?
    so in this eg: SELECT greatest('22', '5', '60', '1000','1') FROM DUAL;----------Ans is : *60*
    select GREATEST('aby', 'john', 'faisal') from dual; --------Ans is john
    how it get these outputs outut,,pls help me
    and how to find the greatest or higest date from one table using greatest function,
    pls explain with an example
    thnz
    Edited by: 821553 on May 17, 2011 3:16 PM
    Edited by: 821553 on May 17, 2011 3:23 PM

    821553 wrote:
    bt i didnt understand yet that how it get the answer '60'
    select GREATEST('aby', 'john', 'faisal') from dual; --------Ans is john
    how it get these outputs?/how it compare the two charctersIf you look at how the data is stored internally...
    SQL> ed
    Wrote file afiedt.buf
      1  with t as (select 'aby' as nm from dual union all
      2             select 'john' from dual union all
      3             select 'faisal' from dual)
      4  --
      5  -- end of test data
      6  --
      7  select nm, dump(nm) as dump_nm
      8* from t
    SQL> /
    NM     DUMP_NM
    aby    Typ=1 Len=3: 97,98,121
    john   Typ=1 Len=4: 106,111,104,110
    faisal Typ=1 Len=6: 102,97,105,115,97,108
    SQL>You can see that the bytes representing each characters have numeric values, and it each of these that are compared from left to right. 'john' starts with a 'j' which is 106 and that's greater than 97 or 102, so john is the greatest.
    If there were two names beginning with 'j' then the next character is compared...
    SQL> ed
    Wrote file afiedt.buf
      1  with t as (select 'aby' as nm from dual union all
      2             select 'john' from dual union all
      3             select 'jon' from dual union all
      4             select 'faisal' from dual)
      5  --
      6  -- end of test data
      7  --
      8  select nm, dump(nm) as dump_nm
      9* from t
    SQL> /
    NM     DUMP_NM
    aby    Typ=1 Len=3: 97,98,121
    john   Typ=1 Len=4: 106,111,104,110
    jon    Typ=1 Len=3: 106,111,110
    faisal Typ=1 Len=6: 102,97,105,115,97,108In this example we have two names beginning "j" which is the greatest of the first character, so the second character is looked at, and there is still two names because they both have the character "o", so it's the 3rd character that is looked at with "h" (104) being compared to "n" (110) to determine that "jon" is the greatest....
    SQL> select greatest('aby','john','jon','faisal') from dual;
    GRE
    jon
    SQL>

  • Performance operations based on Column values in SQL server 2008

    Hi ,
    I have a table which consist of following columns
    ID    Formula              
    Values                 
    DisplayValue
    1                    
    a*b/100       100*12/100    
          null
    2                    
    b*c/100       
    12*4/100              
    null
    I want to perform operation based on column "Values" and save data after operations in new column Name "Display Value" .i.e I want to get the below result . Can anyone please help.
    ID    Formula              
    Values                 
    DisplayValue
    1                    
    a*b/100       100*12/100    
          12
    2                    
    b*c/100       
    12*4/100             
    0.48
    Thanks for the help.
    Regards, Priti A

    Try this,
    create table #mytable (ID int,Formula varchar(10), [Values] varchar(10), DisplayValue decimal(10,4))
    insert into #mytable values(1 ,'a*b/100','100*12/100',null)
    insert into #mytable values(2 ,'b*c/100','12*4/100',null)
    declare @rowcount int=1
    while @rowcount <= (select max(id) from #mytable)
    begin
    declare @expression nvarchar(max)
    select @expression=[values] from #mytable where id = + @rowcount
    declare @sql nvarchar(max)
    set @sql = 'select @result = ' + @expression
    declare @result decimal(10,4)
    exec sp_executesql @sql, N'@result decimal(10,4) output', @result = @result out
    update #mytable set DisplayValue= @result where id = @rowcount
    set @rowcount=@rowcount+1
    end
    select * from #mytable
    Regards, RSingh

  • SCOM 2012 R2 installing on SQL 2012 SP1 - Error Code: 0x80131904, Exception.Message: Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.

    Hi,
    I am getting an issue during a SCOM 2012 R2 installation while creating the SCOM DataWarehouse database. Setup seems to timeout during creating the datawarehouse database. I can see all database files created in windows explorer on the SQL server before
    setup rolls the SCOM install back.
    Has anyone seen this issue before or know how to help resolve it?
    Appreciate your help, below is the SCOM installation log:
    Thanks
    Marc
    [13:27:27]: Always: :Creating Database: OperationsManagerDW
    [13:35:28]: Warn: :Warning:Retry on SQL error -2: Timeout expired.  The timeout period elapsed prior to completion of the operation or the server is not responding.
    [13:43:28]: Warn: :Warning:Retry on SQL error -2: Timeout expired.  The timeout period elapsed prior to completion of the operation or the server is not responding.
    [13:51:29]: Warn: :Warning:Retry on SQL error -2: Timeout expired.  The timeout period elapsed prior to completion of the operation or the server is not responding.
    [13:59:30]: Warn: :Warning:Retry on SQL error -2: Timeout expired.  The timeout period elapsed prior to completion of the operation or the server is not responding.
    [14:07:30]: Warn: :Warning:Retry on SQL error -2: Timeout expired.  The timeout period elapsed prior to completion of the operation or the server is not responding.
    [14:15:31]: Warn: :Warning:Retry on SQL error -2: Timeout expired.  The timeout period elapsed prior to completion of the operation or the server is not responding.
    [14:23:31]: Warn: :Warning:Retry on SQL error -2: Timeout expired.  The timeout period elapsed prior to completion of the operation or the server is not responding.
    [14:31:32]: Warn: :Warning:Retry on SQL error -2: Timeout expired.  The timeout period elapsed prior to completion of the operation or the server is not responding.
    [14:39:32]: Warn: :Warning:Retry on SQL error -2: Timeout expired.  The timeout period elapsed prior to completion of the operation or the server is not responding.
    [14:47:33]: Warn: :Warning:Retry on SQL error -2: Timeout expired.  The timeout period elapsed prior to completion of the operation or the server is not responding.
    [14:55:33]: Error: :DB operations failed with SQL error -2: Timeout expired.  The timeout period elapsed prior to completion of the operation or the server is not responding.
    : Threw Exception.Type: System.Data.SqlClient.SqlException, Exception Error Code: 0x80131904, Exception.Message: Timeout expired.  The timeout period elapsed prior to completion of the operation or the server is not responding.
    [14:55:33]: Error: :StackTrace:   at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
       at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
       at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
       at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
       at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds)
       at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite)
       at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite)
       at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
       at Microsoft.EnterpriseManagement.OperationsManager.Setup.Common.SqlRetryHandler.ExecuteNonQuery(SqlCommand sqlCommand, Int32& result)
       at Microsoft.EnterpriseManagement.OperationsManager.Setup.Common.SqlRetryHandler.Execute[T](SqlCommand sqlCommand, SqlRetryPolicy retryPolicy, GenericExecute`1 genericExecute)
    [14:55:33]: Error: :Inner Exception.Type: System.ComponentModel.Win32Exception, Exception Error Code: 0x80131904, Exception.Message: The wait operation timed out
    [14:55:33]: Error: :InnerException.StackTrace:
    [14:55:33]: Error: :Error:Failed to execute sql command. Setup has reached maximum retry limit.
    [14:55:33]: Warn: :Sql error: 11. Error: -2. Error Message: Timeout expired.  The timeout period elapsed prior to completion of the operation or the server is not responding.
    [14:55:33]: Error: :Exception running sql string
    DECLARE @sql NVARCHAR(MAX);
    SET @sql = 'CREATE DATABASE ' + QUOTENAME(@DatabaseName) + '
        ON PRIMARY(NAME=MOM_DATA,FILENAME=''' + REPLACE(@Filename, '''', '''''') + ''',SIZE=' + CAST(@Size AS VARCHAR) + 'MB,MAXSIZE=UNLIMITED,FILEGROWTH=' + CAST(@FileGrowth AS VARCHAR) + 'MB)
        LOG ON(NAME=MOM_LOG, FILENAME=''' + REPLACE(@LogFilename, '''', '''''') + ''',SIZE=' + CAST(@LogSize AS VARCHAR) + 'MB,MAXSIZE=UNLIMITED,FILEGROWTH=' + CAST(@LogFileGrowth AS VARCHAR) + 'MB)';
    EXEC(@sql);: Threw Exception.Type: System.Data.SqlClient.SqlException, Exception Error Code: 0x80131904, Exception.Message: Timeout expired.  The timeout period elapsed prior to completion of the operation or the server is not responding.
    [14:55:33]: Error: :StackTrace:   at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
       at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
       at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
       at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
       at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds)
       at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite)
       at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite)
       at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
       at Microsoft.EnterpriseManagement.OperationsManager.Setup.Common.SqlRetryHandler.ExecuteNonQuery(SqlCommand sqlCommand, Int32& result)
       at Microsoft.EnterpriseManagement.OperationsManager.Setup.Common.SqlRetryHandler.Execute[T](SqlCommand sqlCommand, SqlRetryPolicy retryPolicy, GenericExecute`1 genericExecute)
       at Microsoft.EnterpriseManagement.OperationsManager.Setup.DBConfigurationHelper.DBConfiguration.RunSqlCommandsList(IEnumerable`1 sqlCommands)
    [14:55:33]: Error: :Inner Exception.Type: System.ComponentModel.Win32Exception, Exception Error Code: 0x80131904, Exception.Message: The wait operation timed out
    [14:55:33]: Error: :InnerException.StackTrace:
    [14:55:33]: Always: :Failed to create and configure the DB with exception.: Threw Exception.Type: System.Data.SqlClient.SqlException, Exception Error Code: 0x80131904, Exception.Message: Timeout expired.  The timeout period elapsed prior to completion
    of the operation or the server is not responding.
    [14:55:33]: Always: :StackTrace:   at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
       at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
       at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
       at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
       at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds)
       at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite)
       at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite)
       at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
       at Microsoft.EnterpriseManagement.OperationsManager.Setup.Common.SqlRetryHandler.ExecuteNonQuery(SqlCommand sqlCommand, Int32& result)
       at Microsoft.EnterpriseManagement.OperationsManager.Setup.Common.SqlRetryHandler.Execute[T](SqlCommand sqlCommand, SqlRetryPolicy retryPolicy, GenericExecute`1 genericExecute)
       at Microsoft.EnterpriseManagement.OperationsManager.Setup.DBConfigurationHelper.DBConfiguration.RunSqlCommandsList(IEnumerable`1 sqlCommands)
       at Microsoft.EnterpriseManagement.OperationsManager.Setup.DWConfigurationHelper.DWConfigurationProcessor.RunAdminScripts(String sqlServerInstance, Nullable`1 port, String databaseName, Int64 dbSize, Int64 logSize, String dbPath, String logPath)
       at Microsoft.EnterpriseManagement.OperationsManager.Setup.DWConfigurationHelper.DWConfigurationProcessor.ConfigureDataWarehouseDatabase(String sqlServerInstance, Nullable`1 port, String databaseName, Int64 dbSize, Int64 logSize, String dbPath,
    String logPath)
    [14:55:33]: Always: :Inner Exception.Type: System.ComponentModel.Win32Exception, Exception Error Code: 0x80131904, Exception.Message: The wait operation timed out
    [14:55:33]: Always: :InnerException.StackTrace:
    [14:55:33]: Error: :CreateDataWarehouse failed: Threw Exception.Type: System.Data.SqlClient.SqlException, Exception Error Code: 0x80131904, Exception.Message: Timeout expired.  The timeout period elapsed prior to completion of the operation or
    the server is not responding.
    [14:55:33]: Error: :StackTrace:   at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
       at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
       at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
       at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
       at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds)
       at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite)
       at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite)
       at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
       at Microsoft.EnterpriseManagement.OperationsManager.Setup.Common.SqlRetryHandler.ExecuteNonQuery(SqlCommand sqlCommand, Int32& result)
       at Microsoft.EnterpriseManagement.OperationsManager.Setup.Common.SqlRetryHandler.Execute[T](SqlCommand sqlCommand, SqlRetryPolicy retryPolicy, GenericExecute`1 genericExecute)
       at Microsoft.EnterpriseManagement.OperationsManager.Setup.DBConfigurationHelper.DBConfiguration.RunSqlCommandsList(IEnumerable`1 sqlCommands)
       at Microsoft.EnterpriseManagement.OperationsManager.Setup.DWConfigurationHelper.DWConfigurationProcessor.RunAdminScripts(String sqlServerInstance, Nullable`1 port, String databaseName, Int64 dbSize, Int64 logSize, String dbPath, String logPath)
       at Microsoft.EnterpriseManagement.OperationsManager.Setup.DWConfigurationHelper.DWConfigurationProcessor.ConfigureDataWarehouseDatabase(String sqlServerInstance, Nullable`1 port, String databaseName, Int64 dbSize, Int64 logSize, String dbPath,
    String logPath)
       at Microsoft.SystemCenter.Essentials.SetupFramework.InstallItemsDelegates.OMDataWarehouseProcessor.CreateDataWarehouse()
    [14:55:33]: Error: :Inner Exception.Type: System.ComponentModel.Win32Exception, Exception Error Code: 0x80131904, Exception.Message: The wait operation timed out
    [14:55:33]: Error: :InnerException.StackTrace:
    [14:55:33]: Error: :FATAL ACTION: CreateDataWarehouse
    [14:55:33]: Error: :FATAL ACTION: DWInstallActionsPostProcessor
    [14:55:33]: Error: :ProcessInstalls: Running the PostProcessDelegate returned false.
    [14:55:33]: Always: :SetErrorType: Setting VitalFailure. currentInstallItem: Data Warehouse Configuration
    [14:55:33]: Error: :ProcessInstalls: Running the PostProcessDelegate for OMDATAWAREHOUSE failed.... This is a fatal item.  Setting rollback.
    marc nalder

    Hi,
    Based on the log, I recommend you use the following way to test SQL connectivity.
    You can use a UDL file to test various connectivity scenarios, create a simple text file, rename the extension from TXT to UDL, fill out the necessary information on the connection tab then test the connection, and troubleshoot as necessary
    if it fails to connect.
    For more information, please review the link below:
    The easy way to test SQL connectivity
    http://blogs.technet.com/b/michaelgriswold/archive/2014/01/06/the-easy-way-to-test-sql-connectivity.aspx
    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.

  • Add multiple users to a certain database in the SQL server in one go

    I wonder if there is any method to add multiple users to a certain database in the SQL server in one go and without using transact code.
    I can add a single user to a certain database “Q” for example by right click on the user “U1” for example then properties then in user mapping tab select
    the database “Q”, so there should be a method to add multiple users ( U1,U2,U3…) to this database?
    Best Regards,
    Ahmad

    Many thanks Visakh16,
    I can do this using the below script, but what I am searching for is do to this without any scripting.
    USE TestDatabase; --Make sure you have the right database
    DECLARE @sql VARCHAR(MAX) = '';
    SELECT @sql = @sql + 'CREATE USER ' + name + ' FOR LOGIN ' + name + ';
    ' +
    'GRANT CREATE TABLE, CREATE PROCEDURE, CREATE VIEW, VIEW DEFINITION TO ' + name + ';
    FROM sys.server_principals p
    WHERE p.type in ('S','U') -- SQL Logins and Windows Login. Do not change!
    and p.name in ('U1','U2','U3'); -- List of names to add. alter to suit
    PRINT @sql; -- Show the statements being executed in the messages pane
    EXEC(@sql); -- Run the statements that have been built
    Thanks,
    Ahmad

  • Cannot create XA data source with MS SQL

    Hello,
    I am currently trying to create a datasource with he XA transactions support. The exception is the same when I'm using the SYSTEM_DRIVER (NetWeaver is using the MS SQL 2005) and when I'm using the user-defined MS SQL JDBC driver. The 'regular' (using tag <jdbc-1.x>) datasources are successfully created, the problem appears only for the XA one.
    This is the part of my data-sources.xml responsible for this data source:
    <data-source>
            <data-source-name>DataSource/SCP</data-source-name>
            <driver-name>SYSTEM_DRIVER</driver-name>
            <init-connections>5</init-connections>
            <max-connections>25</max-connections>
            <sql-engine>Vendor_SQL</sql-engine>
            <jdbc-2.0>
                <xads-class-name>com.microsoft.sqlserver.jdbc.SQLServerXADataSource</xads-class-name>
                <object-factory>com.microsoft.sqlserver.jdbc.SQLServerDataSourceObjectFactory</object-factory>
               <properties>
                    <property>
                        <property-name>serverName</property-name>
                        <property-value>localhost</property-value>
                    </property>
                    <property>
                        <property-name>databaseName</property-name>
                        <property-value>SCP</property-value>
                    </property>
                    <property>
                        <property-name>port</property-name>
                        <property-value>1433</property-value>
                    </property>
                    <property>
                        <property-name>user</property-name>
                        <property-value>myUser</property-value>
                    </property>
                    <property>
                        <property-name>password</property-name>
                        <property-value>myPassword<property-value>
                    </property>
                </properties>
            </jdbc-2.0>
        </data-source>
    Below you can see the stacktrace that appears in the defaultTrace_00.trc:
    Text: [ERROR CODE DPL.DS.5029] Exception in operation startApp with application se.sync/BPE.
    Reason : [ERROR CODE DPL.DS.5029] Exception in operation startApp with application se.sync/BPE.
    [EXCEPTION]
    com.sap.engine.services.deploy.exceptions.ServerDeploymentException: [ERROR CODE DPL.DS.5029] Exception in operation startApp with application se.sync/BPE.
         at com.sap.engine.services.deploy.server.application.ApplicationTransaction.rollbackPart(ApplicationTransaction.java:521)
         at com.sap.engine.services.deploy.server.application.ApplicationTransaction.makeAllPhasesOnOneServer(ApplicationTransaction.java:422)
         at com.sap.engine.services.deploy.server.application.ApplicationTransaction.makeAllPhases(ApplicationTransaction.java:445)
         at com.sap.engine.services.deploy.server.application.ParallelAdapter.super_MakeAllPhases(ParallelAdapter.java:337)
         at com.sap.engine.services.deploy.server.application.StartTransaction.makeAllPhasesImpl(StartTransaction.java:550)
         at com.sap.engine.services.deploy.server.application.ParallelAdapter.runInTheSameThread(ParallelAdapter.java:251)
         at com.sap.engine.services.deploy.server.application.ParallelAdapter.makeAllPhasesAndWait(ParallelAdapter.java:392)
         at com.sap.engine.services.deploy.server.DeployServiceImpl.startApplicationAndWait(DeployServiceImpl.java:3389)
         at com.sap.engine.services.deploy.server.DeployServiceImpl.startApplicationAndWait(DeployServiceImpl.java:3375)
         at com.sap.engine.services.deploy.server.DeployServiceImpl.startApplicationAndWait(DeployServiceImpl.java:3278)
         at com.sap.engine.services.deploy.server.DeployServiceImpl.startApplicationAndWait(DeployServiceImpl.java:3251)
         at com.sap.engine.services.dc.lcm.impl.J2EELCMProcessor.doStart(J2EELCMProcessor.java:99)
         at com.sap.engine.services.dc.lcm.impl.LifeCycleManagerImpl.start(LifeCycleManagerImpl.java:62)
         at com.sap.engine.services.dc.cm.deploy.impl.LifeCycleManagerStartVisitor.visit(LifeCycleManagerStartVisitor.java:34)
         at com.sap.engine.services.dc.cm.deploy.impl.DeploymentItemImpl.accept(DeploymentItemImpl.java:83)
         at com.sap.engine.services.dc.cm.deploy.impl.DefaultDeployPostProcessor.postProcessLCMDeplItem(DefaultDeployPostProcessor.java:80)
         at com.sap.engine.services.dc.cm.deploy.impl.DefaultDeployPostProcessor.postProcess(DefaultDeployPostProcessor.java:56)
         at com.sap.engine.services.dc.cm.deploy.impl.DeployerImpl.doPostProcessing(DeployerImpl.java:741)
         at com.sap.engine.services.dc.cm.deploy.impl.DeployerImpl.performDeploy(DeployerImpl.java:732)
         at com.sap.engine.services.dc.cm.deploy.impl.DeployerImpl.doDeploy(DeployerImpl.java:576)
         at com.sap.engine.services.dc.cm.deploy.impl.DeployerImpl.deploy(DeployerImpl.java:270)
         at com.sap.engine.services.dc.cm.deploy.impl.DeployerImpl.deploy(DeployerImpl.java:192)
         at com.sap.engine.services.dc.cm.deploy.impl.DeployerImplp4_Skel.dispatch(DeployerImplp4_Skel.java:875)
         at com.sap.engine.services.rmi_p4.DispatchImpl._runInternal(DispatchImpl.java:351)
         at com.sap.engine.services.rmi_p4.server.ServerDispatchImpl.run(ServerDispatchImpl.java:70)
         at com.sap.engine.services.rmi_p4.P4Message.process(P4Message.java:62)
         at com.sap.engine.services.rmi_p4.P4Message.execute(P4Message.java:37)
         at com.sap.engine.services.cross.fca.FCAConnectorImpl.executeRequest(FCAConnectorImpl.java:877)
         at com.sap.engine.services.rmi_p4.P4Message.process(P4Message.java:53)
         at com.sap.engine.services.cross.fca.MessageReader.run(MessageReader.java:58)
         at com.sap.engine.core.thread.execution.Executable.run(Executable.java:108)
         at com.sap.engine.core.thread.execution.CentralExecutor$SingleThread.run(CentralExecutor.java:304)
    Caused by: com.sap.engine.services.dbpool.exceptions.BaseDeploymentException: Cannot create DataSource "DataSource/SCP".
         at com.sap.engine.services.dbpool.deploy.ContainerImpl.startDataSources(ContainerImpl.java:1467)
         at com.sap.engine.services.dbpool.deploy.ContainerImpl.prepareStart(ContainerImpl.java:468)
         at com.sap.engine.services.deploy.server.application.StartTransaction.prepareCommon(StartTransaction.java:219)
         at com.sap.engine.services.deploy.server.application.StartTransaction.prepare(StartTransaction.java:179)
         at com.sap.engine.services.deploy.server.application.ApplicationTransaction.makeAllPhasesOnOneServer(ApplicationTransaction.java:420)
         ... 30 more
    Caused by: java.lang.NullPointerException
         at java.lang.Class.forName0(Native Method)
         at java.lang.Class.forName(Class.java:164)
         at com.sap.engine.services.dbpool.deploy.ContainerImpl.startDataSources(ContainerImpl.java:1394)
         ... 34 more
    When I'm looking at the \usr\sap\EE5\J00\exe\mssjdbc\sqljdbc.jar file, I can see both these classes (SQLServerXADataSource and SQLServerDataSourceObjectFactory), so the problem is probably somewhere else. As the exception comes from the native method - does it mean, that the XA extension is not installed correctly on the server (as described [here|http://technet.microsoft.com/en-us/library/aa342335(SQL.90).aspx])?
    Thanks for any help!
    Best Regards,
    -Milosz

    Ok, just to share - the solution was as follows:
    remove the object-factory element
    change property name "port" to "portNumber"
    So, the correct data-sources.xml is as follows:
    <data-source>
         <data-source-name>DataSource/SCP</data-source-name>
         <driver-name>SYSTEM_DRIVER</driver-name>
         <init-connections>5</init-connections>
         <max-connections>25</max-connections>
         <sql-engine>Vendor_SQL</sql-engine>
         <jdbc-2.0>
             <xads-class-name>com.microsoft.sqlserver.jdbc.SQLServerXADataSource</xads-class-name>
             <properties>
                 <property>
                     <property-name>serverName</property-name>
                     <property-value>localhost</property-value>
                 </property>
                 <property>
                     <property-name>databaseName</property-name>
                     <property-value>SCP</property-value>
                 </property>
                 <property>
                     <property-name>portNumber</property-name>
                     <property-value>1433</property-value>
                 </property>
                 <property>
                     <property-name>user</property-name>
                     <property-value>myUser</property-value>
                 </property>
                 <property>
                     <property-name>password</property-name>
                     <property-value>myPassword<property-value>
                  </property>
             </properties>
         </jdbc-2.0>
    </data-source>
    And this works.

  • How to set max size for varchar?

    Hi, all.
         I want to set a type like Varchar(max) in SQL Server.
         How to do that in MAXDB?
    Thanks.

    Hi,
    sorry, I am not familiar with this feature in SQL Server.
    For MaxDB the maximum length for CHAR (n) ASCII is 8000, for CHAR (n) UNICODE is 4000,
    for CLOB is 2GB.
    There is not chance to restrict these maxima.
    If you want to define your 'own' datatype, maybe the concept of DOMAIN (see reference manual --> Data Definition --> CREATE DOMAIN) may help.
    If this does not answer your question, please help us by describing this SQL Server-feature.
    Elke

  • How to store a query containing more than 15000 characters in a variable of nvarchar(max)

    I have the following string and I want to store it in variable using SQL Server 2008 R2 . I can't store this string using variable of nvarchar(max) .
    ' SELECT    A.[EmployeeCode] ,A.[EmployeeId] ,A.[Name],A.[DepartmentCode],A.[DesignationCode]   
    , A.[CompanyCode]  ,A.[Department] ,A.[Designation] ,A.[Entity]
    , A.[GovtAdministrativeAreaCode]   ,A.[WorkingUnitCode],A.[WorkingUnitName]
    , isnull(L.WorkingDays ,0) as  TotalWorkingDays ,isnull(K.DelayHr,0) as DelayHr
    , isnull(J.OTHr,0) as OTHr ,isnull(B.[4Hr],0) as [4Hr]
    , isnull(C.[10Hr],0) as [10Hr] ,isnull(D.[12Hr],0) as [12Hr]
    , isnull(E.NoOfPresent,0) as NoOfPresent   , isnull(F.NoOfAbsent,0 )as NoOfAbsent
    , isnull(G.NoOfLeave ,0) as NoOfLeave , isnull(H.Morning ,0) as Morning
    , isnull(I.Night,0) as Night , isnull(L.[NoOfW/HDay] ,0) as [NoOfW/HDay]
    , isnull(K.NoOfDelay,0) as NoOfDelay , isnull(L.TotalDayAttends,0) as TotalDayAttends
    , isnull(M.[LessThan4Hr] ,0) as [LessThan4Hr]
    , isnull (N.NoOfNoOutTime,0) as NoOfNoOutTime
    INTO '
    +@tableName+'
    FROM
    ( SELECT DISTINCT [EmployeeCode] ,[EmployeeId] ,[Name],[DepartmentCode],[DesignationCode]
      ,[CompanyCode]  ,[Department] ,[Designation] ,[Entity]
      ,[GovtAdministrativeAreaCode]   ,[WorkingUnitCode],[WorkingUnitName]
      FROM [vwHR_DailyAttendanceSummary]
      WHERE AttendanceDate between  dbo.fxn_cDate('''
    +@DateFrom+''')
    and dbo.fxn_cDate('''+@DateTo+''')
    ) A
    LEFT JOIN
    (   SELECT [EmployeeCode]     ,WorkingUnitCode      ,Count([AttendanceDate] ) as [4Hr]
    ,[DepartmentCode] ,[DesignationCode]    ,[GovtAdministrativeAreaCode]  
      FROM [vwHR_DailyAttendanceSummary]
      WHERE AttendanceDate between   dbo.fxn_cDate('''
    +@DateFrom+''')
    and dbo.fxn_cDate('''+@DateTo+''')
      and (DATEDIFF(MINUTE,InTime,OutTime))/60 >=4 and (DATEDIFF(MINUTE,InTime,OutTime))/60 <10
      group by EmployeeCode ,WorkingUnitCode   ,[DepartmentCode] ,[DesignationCode]    ,[GovtAdministrativeAreaCode]  
    ) B ON (B.EmployeeCode=A.EmployeeCode and B.WorkingUnitCode=A.WorkingUnitCode
    and B.DepartmentCode=A.DepartmentCode and B.DesignationCode=A.DesignationCode and B.GovtAdministrativeAreaCode=A.GovtAdministrativeAreaCode)
    LEFT JOIN
    (       SELECT [EmployeeCode]      ,WorkingUnitCode       ,Count([AttendanceDate] ) as [10Hr]
    ,[DepartmentCode] ,[DesignationCode]    ,[GovtAdministrativeAreaCode]     
    FROM [vwHR_DailyAttendanceSummary]
    WHERE AttendanceDate between    dbo.fxn_cDate('''
    +@DateFrom+''')
    and dbo.fxn_cDate('''+@DateTo+''') 
    and (DATEDIFF(MINUTE,InTime,OutTime))/60 >=10 and (DATEDIFF(MINUTE,InTime,OutTime))/60 <12
    group by EmployeeCode,WorkingUnitCode  ,[DepartmentCode] ,[DesignationCode]    ,[GovtAdministrativeAreaCode]   
    )C ON (C.EmployeeCode=A.EmployeeCode and C.WorkingUnitCode=A.WorkingUnitCode
    and C.DepartmentCode=A.DepartmentCode and C.DesignationCode=A.DesignationCode and C.GovtAdministrativeAreaCode=A.GovtAdministrativeAreaCode)
    LEFT JOIN
    (   SELECT [EmployeeCode]     ,WorkingUnitCode   ,Count([AttendanceDate] ) as [12Hr]
    ,[DepartmentCode] ,[DesignationCode]    ,[GovtAdministrativeAreaCode]     
      FROM [vwHR_DailyAttendanceSummary]
      WHERE AttendanceDate between  dbo.fxn_cDate('''
    +@DateFrom+''')
    and dbo.fxn_cDate('''+@DateTo+''')
      and (DATEDIFF(MINUTE,InTime,OutTime))/60 >=12
      group by EmployeeCode,WorkingUnitCode    ,[DepartmentCode] ,[DesignationCode]    ,[GovtAdministrativeAreaCode] 
    ) D on (D.EmployeeCode=A.EmployeeCode and D.WorkingUnitCode=A.WorkingUnitCode
    and D.DepartmentCode=A.DepartmentCode and D.DesignationCode=A.DesignationCode and D.GovtAdministrativeAreaCode=A.GovtAdministrativeAreaCode)
    LEFT JOIN
    (   SELECT [EmployeeCode]  ,WorkingUnitCode   ,COUNT(Status) NoOfPresent
    ,[DepartmentCode] ,[DesignationCode]    ,[GovtAdministrativeAreaCode] 
      FROM [vwHR_DailyAttendanceSummary]
      WHERE Status = ''P'' and AttendanceDate between   dbo.fxn_cDate('''
    +@DateFrom+''')
    and dbo.fxn_cDate('''+@DateTo+''') 
      group by EmployeeCode,WorkingUnitCode,[DepartmentCode] ,[DesignationCode]    ,[GovtAdministrativeAreaCode] 
      ) E on (E.EmployeeCode =A.EmployeeCode and E.WorkingUnitCode=A.WorkingUnitCode
    and E.DepartmentCode=A.DepartmentCode and E.DesignationCode=A.DesignationCode and E.GovtAdministrativeAreaCode=A.GovtAdministrativeAreaCode)
    LEFT JOIN
      (   SELECT [EmployeeCode],WorkingUnitCode  ,COUNT(Status) NoOfAbsent
    ,[DepartmentCode] ,[DesignationCode]    ,[GovtAdministrativeAreaCode] 
      FROM [vwHR_DailyAttendanceSummary]
      WHERE Status = ''A'' and AttendanceDate between  dbo.fxn_cDate('''
    +@DateFrom+''')
    and dbo.fxn_cDate('''+@DateTo+''')
      group by EmployeeCode,WorkingUnitCode  ,[DepartmentCode] ,[DesignationCode]    ,[GovtAdministrativeAreaCode] 
    ) F on (F.EmployeeCode=A.EmployeeCode and F.WorkingUnitCode = A.WorkingUnitCode
    and F.DepartmentCode=A.DepartmentCode and F.DesignationCode=A.DesignationCode and F.GovtAdministrativeAreaCode=A.GovtAdministrativeAreaCode)
    LEFT JOIN
           ( SELECT  la.CompanyCode , la.EmployeeCode ,lad.LeaveDate ,A.WorkingUnitCode,A.DepartmentCode,A.DesignationCode,W.AdminAreaCode
    FROM [vwLMS_EmployeeLeaveInformation] la
    inner JOIN LMS_LeaveApplicationDetail  lad on (lad.LeaveApplicationCode=la.LeaveApplicationCode and lad.ActionType <> ''DELETE'')
    inner join HR_DailyAttendanceSummary A on (A.EmployeeCode=la.EmployeeCode and A.AttendanceDate=lad.LeaveDate and A.ActionType <> ''DELETE'')
    inner join General_WorkingUnit W on (w.WorkingUnitCode=A.WorkingUnitCode and W.ActionType <> ''DELETE'')
    WHERE  la.ApplicationStatus=1 and  la.JobStatus in (1,0)
    and lad.LeaveDate between   dbo.fxn_cDate('''
    +@DateFrom+''')
    and dbo.fxn_cDate('''+@DateTo+''')  
    ) G  on ( G.EmployeeCode=A.EmployeeCode and G.WorkingUnitCode=A.WorkingUnitCode
    and G.DepartmentCode= A.DepartmentCode and G.DesignationCode= A.DesignationCode and G.AdminAreaCode=A.GovtAdministrativeAreaCode)
    LEFT JOIN
    (   SELECT [EmployeeCode] ,WorkingUnitCode ,Count([AttendanceDate] ) as [Morning] 
    ,[DepartmentCode] ,[DesignationCode]    ,[GovtAdministrativeAreaCode]        
      FROM [vwHR_DailyAttendanceSummary]
      WHERE AttendanceDate between  dbo.fxn_cDate('''
    +@DateFrom+''')
    and dbo.fxn_cDate('''+@DateTo+''')
      and (DATEDIFF(MINUTE,InTime,OutTime))/60 >=8 and DATEPART(HH,InTime)=6 and DATEPART(HH,OutTime)>=14
      group by EmployeeCode,WorkingUnitCode    ,[DepartmentCode] ,[DesignationCode]    ,[GovtAdministrativeAreaCode] 
    ) H On (H.EmployeeCode=A.EmployeeCode and H.WorkingUnitCode=A.WorkingUnitCode
    and H.DepartmentCode=A.DepartmentCode and H.DesignationCode=A.DesignationCode and H.GovtAdministrativeAreaCode=A.GovtAdministrativeAreaCode)
    LEFT Join
    (   SELECT [EmployeeCode]   ,WorkingUnitCode       ,Count([AttendanceDate] ) as [Night]
    ,[DepartmentCode] ,[DesignationCode]    ,[GovtAdministrativeAreaCode]          
      FROM [vwHR_DailyAttendanceSummary]
      WHERE AttendanceDate between    dbo.fxn_cDate('''
    +@DateFrom+''')
    and dbo.fxn_cDate('''+@DateTo+''')
      and (DATEDIFF(MINUTE,OutTime,InTime))/60 >=8
      and DATEPART(HH,InTime)>=19
      and DATEPART(HH,OutTime)>=5
      group by EmployeeCode ,WorkingUnitCode ,[DepartmentCode] ,[DesignationCode]    ,[GovtAdministrativeAreaCode] 
    ) I on (I.EmployeeCode=A.EmployeeCode and I.WorkingUnitCode=A.WorkingUnitCode
    and I.DepartmentCode=A.DepartmentCode and I.DesignationCode=A.DesignationCode and I.GovtAdministrativeAreaCode=A.GovtAdministrativeAreaCode)
    LEFT JOIN
    ( SELECT distinCt [EmployeeCode]
    ,sum(TotalOverTime ) as OTHr
    ,WorkingUnitCode
    ,[DepartmentCode] ,[DesignationCode]    ,[GovtAdministrativeAreaCode] 
    FROM vwHR_DayBasisOvertime  
    WHERE AttendanceDate between   dbo.fxn_cDate('''
    +@DateFrom+''')
    and dbo.fxn_cDate('''+@DateTo+''')
    group by EmployeeCode ,WorkingUnitCode ,[DepartmentCode] ,[DesignationCode]    ,[GovtAdministrativeAreaCode] 
    ) J ON (J.EmployeeCode=A.EmployeeCode and J.WorkingUnitCode=A.WorkingUnitCode
    and J.DepartmentCode=A.DepartmentCode and J.DesignationCode=A.DesignationCode and J.GovtAdministrativeAreaCode=A.GovtAdministrativeAreaCode)  
    LEFT JOIN  
    (   SELECT distinCt A.[EmployeeCode]  
    ,DelayHr=CASE
    WHEN sum(DATEDIFF(mi,A.AttendanceDate + A.ShifIn, A.InTime)) >0 THEN SUM( DATEDIFF(mi,A.AttendanceDate +A.ShifIn, A.InTime))
    WHEN sum(DATEDIFF(mi,A.AttendanceDate +A.ShifIn, A.InTime))<0 THEN 0
    END
    ,Count(A.AttendanceDate) as NoOfDelay
    , WorkingUnitCode
    ,[DepartmentCode] ,[DesignationCode]    ,[GovtAdministrativeAreaCode] 
      FROM [vwHR_DailyAttendanceSummary] A
      WHERE A.Status=''D'' AND AttendanceDate between   dbo.fxn_cDate('''
    +@DateFrom+''')
    and dbo.fxn_cDate('''+@DateTo+''') 
      group by A.EmployeeCode ,WorkingUnitCode,[DepartmentCode] ,[DesignationCode]    ,[GovtAdministrativeAreaCode] 
    ) K On (K.EmployeeCode=A.EmployeeCode and K.WorkingUnitCode=A.WorkingUnitCode
    and K.DepartmentCode=A.DepartmentCode and K.DesignationCode=A.DesignationCode and K.GovtAdministrativeAreaCode=A.GovtAdministrativeAreaCode)
    INNER JOIN
    ( select  EmployeeCode ,WorkingUnitCode 
    /*, [A/L Time],[No Of A/L Day],[Total Working Day Time] */
    , [No Of working Day] as WorkingDays
    , ([No Of W Day]+[No Of H Day]) as [NoOfW/HDay]
    ,[Total At] as TotalDayAttends
    ,[DepartmentCode] ,[DesignationCode]    ,[GovtAdministrativeAreaCode] 
    from '
    +@OutPutTableName_WorkingDaysHours+'
    ) L ON (L.EmployeeCode=A.EmployeeCode and l.WorkingUnitCode=A.WorkingUnitCode
    and L.DepartmentCode=A.DepartmentCode and L.DesignationCode=A.DesignationCode and L.GovtAdministrativeAreaCode=A.GovtAdministrativeAreaCode)
    LEFT JOIN
    (   SELECT [EmployeeCode]  ,WorkingUnitCode ,Count([AttendanceDate] ) as [LessThan4Hr] 
    ,[DepartmentCode] ,[DesignationCode]    ,[GovtAdministrativeAreaCode]   
      FROM [vwHR_DailyAttendanceSummary]
      WHERE AttendanceDate between   dbo.fxn_cDate('''
    +@DateFrom+''')
    and dbo.fxn_cDate('''+@DateTo+''')
      and (DATEDIFF(MINUTE,InTime,OutTime))/60 >0 and (DATEDIFF(MINUTE,InTime,OutTime))/60 <4
      group by EmployeeCode,CompanyCode ,WorkingUnitCode    ,[DepartmentCode] ,[DesignationCode]    ,[GovtAdministrativeAreaCode] 
    ) M ON (M.EmployeeCode=A.EmployeeCode and M.WorkingUnitCode=A.WorkingUnitCode
    and M.DepartmentCode=A.DepartmentCode and M.DesignationCode=A.DesignationCode and M.GovtAdministrativeAreaCode=A.GovtAdministrativeAreaCode )
    left join
    ( SELECT EmployeeCode  ,WorkingUnitCode , COUNT(AttendanceDate) as NoOfNoOutTime
    ,[DepartmentCode] ,[DesignationCode]    ,[GovtAdministrativeAreaCode]  
    FROM vwHR_DailyAttendanceSummary
    WHERE  AttendanceDate between dbo.fxn_cDate('''
    +@DateFrom+''')
    and dbo.fxn_cDate('''+@DateTo+''') 
    and OutTime is null
    group by EmployeeCode ,WorkingUnitCode ,[DepartmentCode] ,[DesignationCode]    ,[GovtAdministrativeAreaCode] 
    ) N ON (N.EmployeeCode=A.EmployeeCode and N.WorkingUnitCode=A.WorkingUnitCode
    and N.DepartmentCode=A.DepartmentCode and N.DesignationCode=A.DesignationCode and N.GovtAdministrativeAreaCode=A.GovtAdministrativeAreaCode)

    If you are concatenating multiple strings together to make a nvarchar(max), and the result is too long to store in the largest possible regular regular nvarchar (that is nvarchar(4000), you must be sure the concatenation is done as nvarchar(max).  If
    you don't, each of the concatenations is done according to the type of each operand.  And, if the two things being concatenated are both (for example) nvarchar(20), then the result is nvarchar(40) because 20+20 is 40.  But if the two things being
    concatenated are both nvarchar(3000), the result does not become nvarchar(max), it is nvarchar(4000) - because 3000 + 3000 is 6000, but that's two big, so you get 4000.  For a simple example
    Declare @Result nvarchar(max), @Input1 nvarchar(3000), @Input2 nvarchar(3000);
    Set @Input1 = Replicate('a', 3000);
    Set @Input2 = Replicate('b', 3000);
    Set @Result = @Input1 + @Input2;
    Select 'Test1', Len(@Result), Len(@Input1), Len(@Input2);
    Set @Result = Cast(@Input1 As nvarchar(max)) + @Input2;
    Select 'Test2', Len(@Result), Len(@Input1), Len(@Input2);
    In Test1, the two 3000 character nvarchars are concatenated together, but the result is truncated to nvarchar(4000).  That is then put in an nvarchar(max), but the result is already truncated to 4000 characters, so in Test1 the length of @Result is
    4000.  In Test2, the first operand is converted to nvarchar(max), so the concatenation result is nvarchar(max) and you get the length you expect in @Result (that is, 6000).
    So the solution to your problem is to force the first item in your concatenation to be of type nvarchar(max).  Then the result of the concatenation of the first and second will be nvarchar(max), then SQL concatenates the third term and gets nvarchar(max),
    etc.  So the final result contains the whole string you want.  So you want to do
    CAST(' SELECT A.[EmployeeCode] ,A.[EmployeeId] ,A.[Name],A.[DepartmentCode],A.[DesignationCode]
    , A.[CompanyCode] ,A.[Department] ,A.[Designation] ,A.[Entity]
    , A.[GovtAdministrativeAreaCode] ,A.[WorkingUnitCode],A.[WorkingUnitName]
    , isnull(L.WorkingDays ,0) as TotalWorkingDays ,isnull(K.DelayHr,0) as DelayHr
    , isnull(J.OTHr,0) as OTHr ,isnull(B.[4Hr],0) as [4Hr]
    , isnull(C.[10Hr],0) as [10Hr] ,isnull(D.[12Hr],0) as [12Hr]
    , isnull(E.NoOfPresent,0) as NoOfPresent , isnull(F.NoOfAbsent,0 )as NoOfAbsent
    , isnull(G.NoOfLeave ,0) as NoOfLeave , isnull(H.Morning ,0) as Morning
    , isnull(I.Night,0) as Night , isnull(L.[NoOfW/HDay] ,0) as [NoOfW/HDay]
    , isnull(K.NoOfDelay,0) as NoOfDelay , isnull(L.TotalDayAttends,0) as TotalDayAttends
    , isnull(M.[LessThan4Hr] ,0) as [LessThan4Hr]
    , isnull (N.NoOfNoOutTime,0) as NoOfNoOutTime
    INTO ' AS nvarchar(max))
    +@tableName+'
    --- Etc for the rest of your expression
    Tom

  • Help with using dynamic sql logic in a view please?

    Greetings,
    I want to create a dynamic union using all the databases on server. The following works:
    declare @sqlvarchar(max)
    select
    @sql=IsNull(@sql+'union
    all ','')+'select
    * from  '+name+'.[dbo].[A]''
    inner join '+name+'.[dbo].[B]'' on
    a.f1=b.f1'
    from
    sys.databases
    where
    name
    in(select
    name
    from
    sys.databases)
    exec
    (@sql)
    The problem is I need something tangible, like a view, to query using SSAS later. I've tried to use SELECT into to load a new table with a resulting dataset. It gives me a syntax error - the dynamic part can't be combined with static. I can't use OPENQUERY
    because it all happens on the same server. Assistance would be appreciated. Thanks

    Well, you could regenerate the view each time a database is created or dropped.
    Or you can define your cube using an empty view and load the cube using SSIS, eg with
    Dimension Processing Destination.
    Or you can use something like a CLR TVF inside your view.
    David
    David http://blogs.msdn.com/b/dbrowne/

  • Creating sql query using 3 tables

    There is database (supposed to be relational but it is not) and
    I cannot change the tables and it is very difficult to create SQL query.
    Please, help!
    First table T1
    a1 char 20
    time timestamp
    a2 char 7 (the same as t2.a2 when is trimmed)
    a3 number 5,0
    a4 number 8,4
    a5 number 7,3
    Second table T2
    a2 char 15
    b1 number 1,0
    b2 char 1,0
    b3 char 4
    a3 number 5,0
    Third table T3
    b3 char 4
    c1 char 4
    c2 number 7,3
    c3 number 8,4
    So, I need to create query (is it possible at all!?) from those 3 tables (a1, a2, b1,b2,b3, a4, a5, c2,c3
    where time is within interval (from, to), a3 in interval (1,2,3,4), t2.b3=t3.b3, t1.a2=t2.a2
    group by or sorted by a1, then, a2.
    Any suggestion is welcome!
    Thanks!
    By the way, I will use this query in Crystal Reports.

    As I already mentioned, I received another conditions for the query, and when I create a new one, I
    First table T1
    a1 number 5,0
    a2 char 7 (the same as t2.a2 when is trimmed)
    a3 number 8,4
    a4 number 7,3
    a_time timestamp
    Second table T2
    a2 char 15
    b1 number 1,0
    b2 char 1,0
    b3 char 4
    b4 char 4
    Third table T3
    c1 char 4
    c2 number 7,3
    c3 number 8,4
    b3 char 4
    where if c1='MIN' c2, c3 return min values,
    and if c1='MAX' c2,c3 return max values
    SQL query:
    select t1.a1, t1.a2, t2.b1, t2.b2, t2.b3, t1.a3, t1.a4, t3.c1,
    t3.c2, t3.c3, t2.b4
    from t1, t2, t3
    where (TRIM(t1.a2)=TRIM(t2.a2)
    and t1.a1=19
    and ((to_char(t1.a_time, 'YYYY-MM-DD') >= '2006-03-15')
    and (to_char(t1.a_time, 'YYYY-MM-DD') <= '2006-03-16')))
    and t3.b3=t2.b3)
    order by t1.a_time
    Result set:
    a1, a2, b1, b2, b3, a3, a4, c1('MAX'), c2', c3', b4
    a1, a2, b1, b2, b3, a3, a4, c1('MIN'), c2", c3", b4
    So when I executed SQL query it returns 2 rows for the same a2.
    I want to get 1 row for each a2 together with c3 (c4) min and c3 (c4) max values.
    How to name columns for c2 min and c2 max (the same for c3) in order to retreive 1 row per a2 value, something like this:
    a1, a2, b1, b2, b3, a3, a4, c2min, c2max, c3min, c3max, b4
    Thanks

  • SQL question that's always bugged  me

    SQL> select * from customer where customer_id = 4;
    no rows selected
    SQL> select max(customer_id) from customer where customer_id = 4;
    MAX(CUSTOMER_ID)
    SQL>
    WHY!!!!!
    This has been driving me nuts, for the past hour or so trying to hunt down a bug in some code, it turned out that due to the max() a function wasn't raising a NO_DATA_FOUND exception and failing elsewhere with an obscure error because of it. after a "select max() into" clause, we have to add an additional check to see if the value it selected into is null or not..... how dumb is that?
    ok, I've calmed down now.

    Michael:
    Both seem quite reasonable to me. Conceptually. ignoring the GROUP BY bit, a COUNT works like:
    DECLARE
       l_cnt NUMBER :=0;
    BEGIN
       FOR r IN (<query>) LOOP
          l_cnt := l_cnt + 1;
       END LOOP;
       RETURN l_cnt;
    END;While a MAX or MIN works like:
    DECLARE
       l_max VARCHAR2(4000) := NULL;
       FOR r IN (<query>) LOOP
          IF r.max_col > l_max THEN
            l_max := r.max_col;
          END IF;
       END LOOP;
       RETURN l_max;
    END;I'm sure that Oracle has more efficient algorithms, but the point is that the aggregate functions iterate over a result set to generate the result The fact that the result set is empty in some cases doesn't really matter.
    Think about what it would mean if some aggregates, like COUNT or SUM, never threw NO_DATA_FOUND, but others like MAX OR MIN did if there were no rows matching the criteria.
    In both of your example cases. grouping does take place:
    SQL> SELECT COUNT(*) FROM employees;
      COUNT(*)
           107
    Execution Plan
       0      SELECT STATEMENT Optimizer=CHOOSE (Cost=1 Card=1)
       1    0   SORT (AGGREGATE)
       2    1     INDEX (FULL SCAN) OF 'EMP_EMAIL_UK' (UNIQUE) (Cost=1 Card=107)It is just that the group is all of the records.
    John
    Message was edited by:
    John Spencer
    Added the grouping comments.

Maybe you are looking for

  • Free goods configuration, plz help

    Pl help for this scenerio: 1) Sales order - Material A - Qty 23     Free Goods - Material B - Qty 3 Nos and Material C - Qty 1 No     There is a scale also. 2) Sales order - Material A and Material B - combined qty - 30 Nos     Free Goods - Material

  • Cost is not a part of PO, but to be added in material, how?

    Dear all, Cost which is not a part of PO but to be added in material, how that can be done... is it through statistical condition types, kindly explain how this can be done? regards, Archu

  • Convert iphoto slide show to mov format?

    hello, I just want to ask that, can I convert iphoto slide show into mov format??? I tried to select all pics, and export them as a mov, but the problem is, in the iphoto slide show, the pics can be moved and fit the screen size, but when I i export

  • User - Role - view only

    Dear all, i have a question. I am developing a application to view some data from the database. This application will be on the laptops of all the people that are working all over the country. To prevent that a stolen laptop is used fore decompiling

  • I bought a MacBook yesterday and can't find where the a/c cord goes into it

    Two different type of power cords came with my MacBook I see the connection for the what appears to be the battery charger; yet, If I want to run off a/c I assume apple gave me this other a/c power cord to plug in somewhere to the MacBook it has a gr