SQL Server Error 3930

Hi Everyone,
I am getting the following error while inserting rows in a table
"Unexpected error: 3930-"The current transaction cannot be committed and cannot support operations that write to the log file. Roll back the transaction."
The table has an index that is fired on update.
Code
BEGIN TRY
        INSERT INTO [dbo].[Sample_Table]
                   ([Lang]
                   ,[StuCode]
                   ,[StuID]
                   ,[StuName]
                   ,[DisplayNameLocal]
                   ,[DisplayNameInternational]
                   ,[CityName]
                   ,[RegionName]
                   ,[CountryCode]
                   ,[MetroCodeBool]
                   ,[StatusCode]
                   ,[UpdateDate]
                   ,[LastUpdatedBy])
             VALUES
                   (@pLang
                   ,@pStuCode
                   ,@pStuID
                   ,@pStuName
                   ,@pDisplayNameLocal
                   ,@pDisplayNameInternational
                   ,@pCityName
                   ,@pRegionName
                   ,@pCountryCode
                   ,@pMetroCodeBool
                   ,@pStatusCode
                   ,@pUpdateDate
                   ,@pLastUpdatedBy);
            END TRY
            BEGIN CATCH
            select * from AirportNameLoc where AirportCode=@pAirportCode and LangID=@pLangID        
            END CATCH
Please help.
Thanks!!

Hi NiViV,
I find a similar issue and post it here, hope it’s helpful.
http://social.technet.microsoft.com/Forums/en-US/ebefc980-130d-4e28-a3e2-ef42296e5657/trigger-the-current-transaction-cannot-be-committed-and-cannot-support-operations-that-write-to?forum=transactsql
This is a forum for Visio, not for SQL. If you want to receive about this issue, I suggest you posting it in SQL Server forum.
http://social.technet.microsoft.com/Forums/en-US/home?category=sqlserver
The reason why we recommend posting appropriately is you will get the most qualified pool of respondents, and other partners who read the forums regularly can either share
their knowledge or learn from your interaction with us. Thank you for your understanding.
If there is anything I can do for you regarding this issue, feel free to post back.
Best regards,
Greta Ge
TechNet Community Support
It's recommended to download and install
Configuration Analyzer Tool (OffCAT), which is developed by Microsoft Support teams. Once the tool is installed, you can run it at any time to scan for hundreds of known issues in Office
programs.

Similar Messages

  • Connection failed: SQLState:'01000' SQL Server Error:67 [Microsoft]ODBC SQL Server Driver][DBNETLIB]ConnectionOpen (Connect()). Connection failed: SQLState:'08001' SQL Server Error:17 [Microsoft]ODBC SQL Server Driver][DBNETLIB]SQL Server does not exist o

    Help,
    setup a new sql server 2012 on a windows 2012r2 server to replace old sql server 2005 on an old windows server 2003 machine.  When i test the ODBC connection locally on the server it works fine, however when i try to connect via windows 7 client machine
    i get the following error:
    Connection failed:
    SQLState:'01000'
    SQL Server Error:67
    [Microsoft]ODBC SQL Server Driver][DBNETLIB]ConnectionOpen
    (Connect()).
    Connection failed:
    SQLState:'08001'
    SQL Server Error:17
    [Microsoft]ODBC SQL Server Driver][DBNETLIB]SQL Server does not exist or access denied
    I think it must be a permissions thing, I've turned off the firewall for now and still no difference, 've also made sure remote connection is enabled.  I can connect to the other sql server in studio manager on the new machine however, i can't go do
    the same in the old server, says:
    cannot connect to hbfsqlpro1\hbfsqlpro1
    Additonal information a network related or instance specifc error occured while establising a connection to SQL server.  The server was not found or was not accessible.  Verify that the instance name is correct and that SQL server is configured to
    allow remote connections. (provider:SQL Network Interfaces, error 26 - error locationg server/instance specified) (Microsoft SQL server)
    the instance is def correct, as that is what i use to connect locally on the new machine and what it comes up on the studio manager on the new machine.  STarting to pull my hair out somewhat, i'm sure it's something really simple! 

    Hello,
    You are trying to connect to a named instance. Make sure the SQL Server Browser service is started on the SQL Server computer.
    Make sure TCP/IP is enabled.
    http://msdn.microsoft.com/en-us/library/ms191294(v=sql.110).aspx
    Try to disable Windows Firewall or security software on both, SQL Server instance and client computer.
    Test basic connectivity too. Try to ping from the client computer to the SQL Server computer.
    Hope this helps.
    Regards,
    Alberto Morillo
    SQLCoffee.com

  • Wait on the Database Engine recovery handle failed. Check the SQL server error log for potential causes in SQL Server 2012 Developer Edition

    I m using SQL Server 2012 Developer Edition. Even I tried 2012 express and enterprise edition but all
    gave same error. I browsed msdn blog. But nothing help me out.
    Below is the error log details--
    Overall summary:
      Final result:                  Failed: see details below
      Exit code (Decimal):           -2061893606
      Start time:                    2013-10-21 12:58:05
      End time:                      2013-10-21 13:52:30
      Requested action:              Install
    Setup completed with required actions for features.
    Troubleshooting information for those features:
      Next step for RS:              Use the following information to resolve the error, uninstall this feature, and then run the setup process again.
      Next step for SQLEngine:       Use the following information to resolve the error, uninstall this feature, and then run the setup process again.
      Next step for DQ:              Use the following information to resolve the error, uninstall this feature, and then run the setup process again.
      Next step for FullText:        Use the following information to resolve the error, uninstall this feature, and then run the setup process again.
      Next step for Replication:     Use the following information to resolve the error, uninstall this feature, and then run the setup process again.
    Machine Properties:
      Machine name:                  CROY-TOSH
      Machine processor count:       4
      OS version:                    Windows 7
      OS service pack:               Service Pack 1
      OS region:                     United States
      OS language:                   English (United States)
      OS architecture:               x64
      Process architecture:          64 Bit
      OS clustered:                  No
    Product features discovered:
      Product              Instance             Instance ID                    Feature                
                     Language             Edition              Version         Clustered 
    Package properties:
      Description:                   Microsoft SQL Server 2012 Service Pack 1
      ProductName:                   SQL Server 2012
      Type:                          RTM
      Version:                       11
      SPLevel:                       0
      Installation location:         C:\Users\CRoy\Downloads\SQL Server 2012 Developer Edition (x86 and x64) - DVD (English)\x64\setup\
      Installation edition:          Developer
    Product Update Status:
      None discovered.
    User Input Settings:
      ACTION:                        Install
      ADDCURRENTUSERASSQLADMIN:      false
      AGTSVCACCOUNT:                 NT Service\SQLSERVERAGENT
      AGTSVCPASSWORD:                *****
      AGTSVCSTARTUPTYPE:             Manual
      ASBACKUPDIR:                   C:\Program Files\Microsoft SQL Server\MSAS11.MSSQLSERVER\OLAP\Backup
      ASCOLLATION:                   Latin1_General_CI_AI
      ASCONFIGDIR:                   C:\Program Files\Microsoft SQL Server\MSAS11.MSSQLSERVER\OLAP\Config
      ASDATADIR:                     C:\Program Files\Microsoft SQL Server\MSAS11.MSSQLSERVER\OLAP\Data
      ASLOGDIR:                      C:\Program Files\Microsoft SQL Server\MSAS11.MSSQLSERVER\OLAP\Log
      ASPROVIDERMSOLAP:              1
      ASSERVERMODE:                  MULTIDIMENSIONAL
      ASSVCACCOUNT:                  NT Service\MSSQLServerOLAPService
      ASSVCPASSWORD:                 <empty>
      ASSVCSTARTUPTYPE:              Automatic
      ASSYSADMINACCOUNTS:            CRoy-TOSH\CRoy
      ASTEMPDIR:                     C:\Program Files\Microsoft SQL Server\MSAS11.MSSQLSERVER\OLAP\Temp
      BROWSERSVCSTARTUPTYPE:         Disabled
      CLTCTLRNAME:                   ROY
      CLTRESULTDIR:                  C:\Program Files (x86)\Microsoft SQL Server\DReplayClient\ResultDir\
      CLTSTARTUPTYPE:                Manual
      CLTSVCACCOUNT:                 NT Service\SQL Server Distributed Replay Client
      CLTSVCPASSWORD:                <empty>
      CLTWORKINGDIR:                 C:\Program Files (x86)\Microsoft SQL Server\DReplayClient\WorkingDir\
      COMMFABRICENCRYPTION:          0
      COMMFABRICNETWORKLEVEL:        0
      COMMFABRICPORT:                0
      CONFIGURATIONFILE:             C:\Program Files\Microsoft SQL Server\110\Setup Bootstrap\Log\20131021_125116\ConfigurationFile.ini
      CTLRSTARTUPTYPE:               Manual
      CTLRSVCACCOUNT:                NT Service\SQL Server Distributed Replay Controller
      CTLRSVCPASSWORD:               <empty>
      CTLRUSERS:                     CRoy-TOSH\CRoy
      ENABLERANU:                    false
      ENU:                           true
      ERRORREPORTING:                true
      FEATURES:                      SQLENGINE, REPLICATION, FULLTEXT, DQ, AS, RS, RS_SHP, RS_SHPWFE, DQC, BIDS, CONN, IS, BC, SDK, BOL, SSMS, ADV_SSMS, DREPLAY_CTLR, DREPLAY_CLT, SNAC_SDK, MDS
      FILESTREAMLEVEL:               2
      FILESTREAMSHARENAME:           MSSQLSERVER
      FTSVCACCOUNT:                  NT Service\MSSQLFDLauncher
      FTSVCPASSWORD:                 <empty>
      HELP:                          false
      IACCEPTSQLSERVERLICENSETERMS:  false
      INDICATEPROGRESS:              false
      INSTALLSHAREDDIR:              C:\Program Files\Microsoft SQL Server\
      INSTALLSHAREDWOWDIR:           C:\Program Files (x86)\Microsoft SQL Server\
      INSTALLSQLDATADIR:             <empty>
      INSTANCEDIR:                   C:\Program Files\Microsoft SQL Server\
      INSTANCEID:                    MSSQLSERVER
      INSTANCENAME:                  MSSQLSERVER
      ISSVCACCOUNT:                  NT Service\MsDtsServer110
      ISSVCPASSWORD:                 <empty>
      ISSVCSTARTUPTYPE:              Automatic
      MATRIXCMBRICKCOMMPORT:         0
      MATRIXCMSERVERNAME:            <empty>
      MATRIXNAME:                    <empty>
      NPENABLED:                     0
      PID:                           *****
      QUIET:                         false
      QUIETSIMPLE:                   false
      ROLE:                          <empty>
      RSINSTALLMODE:                 DefaultNativeMode
      RSSHPINSTALLMODE:              SharePointFilesOnlyMode
      RSSVCACCOUNT:                  NT Service\ReportServer
      RSSVCPASSWORD:                 <empty>
      RSSVCSTARTUPTYPE:              Automatic
      SAPWD:                         *****
      SECURITYMODE:                  SQL
      SQLBACKUPDIR:                  <empty>
      SQLCOLLATION:                  Latin1_General_CI_AI
      SQLSVCACCOUNT:                 NT Service\MSSQLSERVER
      SQLSVCPASSWORD:                *****
      SQLSVCSTARTUPTYPE:             Automatic
      SQLSYSADMINACCOUNTS:           CRoy-TOSH\CRoy
      SQLTEMPDBDIR:                  <empty>
      SQLTEMPDBLOGDIR:               <empty>
      SQLUSERDBDIR:                  <empty>
      SQLUSERDBLOGDIR:               <empty>
      SQMREPORTING:                  false
      TCPENABLED:                    0
      UIMODE:                        Normal
      UpdateEnabled:                 true
      UpdateSource:                  MU
      X86:                           false
      Configuration file:            C:\Program Files\Microsoft SQL Server\110\Setup Bootstrap\Log\20131021_125116\ConfigurationFile.ini
    Detailed results:
      Feature:                       Management Tools - Complete
      Status:                        Passed
      Feature:                       Client Tools Connectivity
      Status:                        Passed
      Feature:                       Client Tools SDK
      Status:                        Passed
      Feature:                       Client Tools Backwards Compatibility
      Status:                        Passed
      Feature:                       Management Tools - Basic
      Status:                        Passed
      Feature:                       SQL Server Data Tools
      Status:                        Passed
      Feature:                       Reporting Services - Native
      Status:                        Failed: see logs for details
      Reason for failure:            An error occurred for a dependency of the feature causing the setup process for the feature to fail.
      Next Step:                     Use the following information to resolve the error, uninstall this feature, and then run the setup process again.
      Component name:                SQL Server Database Engine Services Instance Features
      Component error code:          0x851A001A
      Error description:             Wait on the Database Engine recovery handle failed. Check the SQL Server error log for potential causes.
      Error help link:               http://go.microsoft.com/fwlink?LinkId=20476&ProdName=Microsoft+SQL+Server&EvtSrc=setup.rll&EvtID=50000&ProdVer=11.0.3128.0&EvtType=0xD15B4EB2%400x4BDAF9BA%401306%4026&EvtType=0xD15B4EB2%400x4BDAF9BA%401306%4026
      Feature:                       Database Engine Services
      Status:                        Failed: see logs for details
      Reason for failure:            An error occurred during the setup process of the feature.
      Next Step:                     Use the following information to resolve the error, uninstall this feature, and then run the setup process again.
      Component name:                SQL Server Database Engine Services Instance Features
      Component error code:          0x851A001A
      Error description:             Wait on the Database Engine recovery handle failed. Check the SQL Server error log for potential causes.
      Error help link:               http://go.microsoft.com/fwlink?LinkId=20476&ProdName=Microsoft+SQL+Server&EvtSrc=setup.rll&EvtID=50000&ProdVer=11.0.3128.0&EvtType=0xD15B4EB2%400x4BDAF9BA%401306%4026&EvtType=0xD15B4EB2%400x4BDAF9BA%401306%4026
      Feature:                       Data Quality Services
      Status:                        Failed: see logs for details
      Reason for failure:            An error occurred for a dependency of the feature causing the setup process for the feature to fail.
      Next Step:                     Use the following information to resolve the error, uninstall this feature, and then run the setup process again.
      Component name:                SQL Server Database Engine Services Instance Features
      Component error code:          0x851A001A
      Error description:             Wait on the Database Engine recovery handle failed. Check the SQL Server error log for potential causes.
      Error help link:               http://go.microsoft.com/fwlink?LinkId=20476&ProdName=Microsoft+SQL+Server&EvtSrc=setup.rll&EvtID=50000&ProdVer=11.0.3128.0&EvtType=0xD15B4EB2%400x4BDAF9BA%401306%4026&EvtType=0xD15B4EB2%400x4BDAF9BA%401306%4026
      Feature:                       Full-Text and Semantic Extractions for Search
      Status:                        Failed: see logs for details
      Reason for failure:            An error occurred for a dependency of the feature causing the setup process for the feature to fail.
      Next Step:                     Use the following information to resolve the error, uninstall this feature, and then run the setup process again.
      Component name:                SQL Server Database Engine Services Instance Features
      Component error code:          0x851A001A
      Error description:             Wait on the Database Engine recovery handle failed. Check the SQL Server error log for potential causes.
      Error help link:               http://go.microsoft.com/fwlink?LinkId=20476&ProdName=Microsoft+SQL+Server&EvtSrc=setup.rll&EvtID=50000&ProdVer=11.0.3128.0&EvtType=0xD15B4EB2%400x4BDAF9BA%401306%4026&EvtType=0xD15B4EB2%400x4BDAF9BA%401306%4026
      Feature:                       SQL Server Replication
      Status:                        Failed: see logs for details
      Reason for failure:            An error occurred for a dependency of the feature causing the setup process for the feature to fail.
      Next Step:                     Use the following information to resolve the error, uninstall this feature, and then run the setup process again.
      Component name:                SQL Server Database Engine Services Instance Features
      Component error code:          0x851A001A
      Error description:             Wait on the Database Engine recovery handle failed. Check the SQL Server error log for potential causes.
      Error help link:               http://go.microsoft.com/fwlink?LinkId=20476&ProdName=Microsoft+SQL+Server&EvtSrc=setup.rll&EvtID=50000&ProdVer=11.0.3128.0&EvtType=0xD15B4EB2%400x4BDAF9BA%401306%4026&EvtType=0xD15B4EB2%400x4BDAF9BA%401306%4026
      Feature:                       Master Data Services
      Status:                        Passed
      Feature:                       Distributed Replay Client
      Status:                        Passed
      Feature:                       Distributed Replay Controller
      Status:                        Passed
      Feature:                       Integration Services
      Status:                        Passed
      Feature:                       Data Quality Client
      Status:                        Passed
      Feature:                       Analysis Services
      Status:                        Passed
      Feature:                       Reporting Services - SharePoint
      Status:                        Passed
      Feature:                       Reporting Services Add-in for SharePoint Products
      Status:                        Passed
      Feature:                       SQL Browser
      Status:                        Passed
      Feature:                       Documentation Components
      Status:                        Passed
      Feature:                       SQL Writer
      Status:                        Passed
      Feature:                       SQL Client Connectivity
      Status:                        Passed
      Feature:                       SQL Client Connectivity SDK
      Status:                        Passed
    Rules with failures:
    Global rules:
    Scenario specific rules:
    Rules report file:               C:\Program Files\Microsoft SQL Server\110\Setup Bootstrap\Log\20131021_125116\SystemConfigurationCheck_Report.htm

    Hi,
    This 3rd time I followed this link. But nothing new, same error.
    Can you please tell me how to do follow, I cannt do the 1st step, how to change the local system to windows level account, vice-versa. It is shown mine as
    Server Configuration Manager(Local) 
    From here I folllowed the steps ---[I cannt insert link/image :-(]
    SQL 2008/R2 setup fails with "Wait on the database engine recovery handle failed" 
    If I right clicked on SQL Server Service, there is no option to change the account. 
    Hello,
    Thanks for your patience,did you tried stesp mentioned in below article
    http://blogs.msdn.com/b/sqljourney/archive/2012/03/16/sql-2008-r2-setup-fails-with-quot-wait-on-the-database-engine-recovery-handle-failed-quot.aspx
    To resolve it, follow these steps:-
    When the installation throws this error, click on OK and allow it to proceed. It will fail for Database Engine, but the SQL Server service should have
    been created. Check the Services console.
    If the service is present, perform the following steps:-
    1. Go to SQL Server Configuration manager, right click on the SQL Server service, and change the service account (if it is local system, give
    it a windows level account, and vice-versa). It might throw a WMI error but you will see the account getting updated anyway. If not, then use the Services console. Change the account for SQL Agent as well.
    Use this link to change sql server service account
    http://technet.microsoft.com/en-us/library/ms345578.aspx
    2. Next, try to start the service. It should come online.
    3. However, you will not be able to log in to the SQL Server
    4. Now stop the service and start it from the command prompt using -m -c -T3608 parameters.
    5. Now try logging in to the server using admin connection from sqlcmd (sqlcmd admin:<server name>\<instance name> ...)
    6. Once logged in, use the sp_addsrvrolemember '<domain\username>','sysadmin'.
    Also add the builtin/administrators to the sysadmin role
    7. Now stop the service from the command prompt and start it from SQL Server configuration manager
    You should be able to log in to the server now.
    Hope this helps someone.
    Please revert if it helps or even if it does not
    Please mark this reply as the answer or vote as helpful, as appropriate, to make it useful for other readers

  • The SELECT permissions was denied on the object 'extended_properties', database 'mssqlsystemresource', schema 'sys'.(Microsoft SQL Server, Error:229

    I have a SQL Server connected intro a Windows Server 2003 Domain Active Directory, the server holds a default instance with a single Database, the SQL Server is 2005 Std Edition, and is using mix mode Authentification, then I able to create SQL Native Users
    and Invoque Windows Domain Users also.
    The Goal of this project is remove the sysadmin Server role for all the Windows Domain Users, to give then a more granular secure model but at the moment is this only way to connect at the Data Base Server.
    I already create Native SQL Servers users without any problem!, they respect Securable Setting, Server Roles, User Mapping, everything...Just when I create a Login Profile form a Domain Users and apply the same setting, I get this error...
    The SELECT permissions was denied on the object 'extended_properties', database 'mssqlsystemresource', schema 'sys'.(Microsoft SQL Server, Error:229)
    But if the user have sysadmin Server Rol he can sing over the server without any issue, I review the .sys view extended_properties and "Public" is the only Database Role placed.
    Any Idea if I need change any Setting in the Secure in SQL Master DataBase? or which is the issue witjh this matter?
    Thank in advance for your help!

    Since there are so many possibilities for what might be wrong.  Here's another possibility to look at.  I ran into something where I had set up my own roles on a database.  (For instance, "Administrator", "Manager", "DataEntry",
    "Customer", each with their own kinds of limitations)  The only ones who could use it were "Manager" role or above--because they were also set up as sysadmin because they were adding users to the database (and they were highly trusted). 
    Also, the users that were being added were Windows Domain users--using their domain credentials.  (Everyone with access to the database had to be on our domain, but not everyone on the domain had access to the database--and only a few of them had access
    to change it.)
    Anyway, this working system suddenly stopped working and I was getting error messages similar to the above.  What I ended up doing that solved it was to go through all the permissions for the "public" role in that database and add those permissions
    to all of the roles that I had created.  I know that everyone is supposed to be in the "public" role even though you can't add them (or rather, you can "add" them, but they won't "stay added").
    So, in "SQL Server Management Studio", I went into my application's database, in other words (my localized names are obscured within <> brackets): "<Computername> (SQL Server <version> - sa)"\Databases\<MyAppDB>\Security\Roles\Database
    Roles\public".  Right-click on "public" and select "Properties".  In the "Database Role Properties - public" dialog, select the "Securables" page.  Go through the list and for each element in the
    list, come up with an SQL "Grant" statement to grant exactly that permission to another role.  So, for instance, there is a scalar function "[dbo].[fn_diagramobjects]" on which the "public" role has "Execute" privilege. 
    So, I added the following line:   
    EXEC ( 'GRANT EXECUTE ON [dbo].[fn_diagramobjects] TO [' + @RoleName + '];' )
    Once I had done this for all the elements in the "Securables" list, I wrapped that up in a while loop on a cursor selecting through all the roles in my roles table.  This explicitly granted all the permissions of the "public" role to
    my database roles.  At that point, all my users were working again (even after I removed their "sysadmin" access--done as a temporary measure while I figured out what happened.)
    I'm sure there's a better (more elegant) way to do this by doing some kind of a query on the database objects and selecting on the public role, but after about half and hour of investigating, I wasn't figuring it out, so I just did it the brute-force method. 
    In case it helps someone else, here's my code.
    CREATE PROCEDURE [dbo].[GrantAccess]
    AS
    DECLARE @AppRoleName AS sysname
    DECLARE AppRoleCursor CURSOR LOCAL SCROLL_LOCKS FOR
    SELECT AppRoleName FROM [dbo].[RoleList];
    OPEN AppRoleCursor
    FETCH NEXT FROM AppRoleCursor INTO @AppRoleName
    WHILE @@FETCH_STATUS = 0
    BEGIN
    EXEC ( 'GRANT EXECUTE ON [dbo].[fn_diagramobjects] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT EXECUTE ON [dbo].[sp_alterdiagram] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT EXECUTE ON [dbo].[sp_creatediagram] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT EXECUTE ON [dbo].[sp_dropdiagram] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT EXECUTE ON [dbo].[sp_helpdiagramdefinition] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT EXECUTE ON [dbo].[sp_helpdiagrams] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT EXECUTE ON [dbo].[sp_renamediagram] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[all_columns] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[all_objects] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[all_parameters] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[all_sql_modules] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[all_views] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[allocation_units] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[assemblies] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[assembly_files] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[assembly_modules] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[assembly_references] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[assembly_types] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[asymmetric_keys] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[certificates] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[change_tracking_tables] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[check_constraints] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[column_type_usages] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[column_xml_schema_collection_usages] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[columns] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[computed_columns] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[conversation_endpoints] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[conversation_groups] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[conversation_priorities] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[crypt_properties] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[data_spaces] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[database_audit_specification_details] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[database_audit_specifications] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[database_files] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[database_permissions] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[database_principal_aliases] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[database_principals] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[database_role_members] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[default_constraints] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[destination_data_spaces] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[event_notifications] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[events] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[extended_procedures] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[extended_properties] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[filegroups] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[foreign_key_columns] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[foreign_keys] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[fulltext_catalogs] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[fulltext_index_catalog_usages] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[fulltext_index_columns] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[fulltext_index_fragments] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[fulltext_indexes] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[fulltext_stoplists] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[fulltext_stopwords] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[function_order_columns] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[identity_columns] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[index_columns] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[indexes] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[internal_tables] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[key_constraints] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[key_encryptions] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[message_type_xml_schema_collection_usages] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[module_assembly_usages] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[numbered_procedure_parameters] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[numbered_procedures] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[objects] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[parameter_type_usages] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[parameter_xml_schema_collection_usages] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[parameters] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[partition_functions] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[partition_parameters] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[partition_range_values] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[partition_schemes] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[partitions] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[plan_guides] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[procedures] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[remote_service_bindings] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[routes] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[schemas] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[service_contract_message_usages] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[service_contract_usages] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[service_contracts] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[service_message_types] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[service_queue_usages] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[service_queues] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[services] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[spatial_index_tessellations] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[spatial_indexes] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[sql_dependencies] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[sql_modules] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[stats] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[stats_columns] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[symmetric_keys] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[synonyms] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[syscolumns] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[syscomments] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[sysconstraints] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[sysdepends] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[sysfilegroups] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[sysfiles] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[sysforeignkeys] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[sysfulltextcatalogs] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[sysindexes] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[sysindexkeys] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[sysmembers] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[sysobjects] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[syspermissions] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[sysprotects] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[sysreferences] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[system_columns] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[system_objects] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[system_parameters] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[system_sql_modules] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[system_views] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[systypes] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[sysusers] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[table_types] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[tables] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[transmission_queue] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[trigger_events] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[triggers] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[type_assembly_usages] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[types] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[views] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[xml_indexes] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[xml_schema_attributes] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[xml_schema_collections] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[xml_schema_component_placements] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[xml_schema_components] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[xml_schema_elements] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[xml_schema_facets] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[xml_schema_model_groups] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[xml_schema_namespaces] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[xml_schema_types] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[xml_schema_wildcard_namespaces] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[xml_schema_wildcards] TO [' + @AppRoleName + '];' )
    FETCH NEXT FROM AppRoleCursor INTO @AppRoleName
    END
    CLOSE AppRoleCursor
    RETURN 0
    GO
    Once that is in the system, I just needed to "Exec GrantAccess" to make it work.  (Of course, I have a table [RoleList] which contains a "AppRoleName" field that contains the names of the database roles.)
    So, the mystery remains: why did all my users lose their "public" role and why could I not give it back to them?  Was this part of an update to SQL Server 2008 R2?  Was it because I ran another script to delete each user and add them back
    so to refresh their connection with the domain?  Well, this solves the issue for now.
    One last warning: you probably should check the "public" role on your system before running this to make sure there isn't something missing or wrong, here.  It's always possible something is different about your system.
    Hope this helps someone else.

  • The SELECT permission was denied on the object 'extended_properties', database 'mssqlsystemresource', schema 'sys'. (Microsoft SQL Server, Error: 229)

    I have created a user and given him the owner rights for the database.  Though I can LogIn as the user, I cannot access the databases.  I am having the error mesage:
    Failed to retrieve data for this request. (Microsoft.SqlServer.Management.Sdk.Sfc)
    For help, click:
    http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&LinkId=20476
    ADDITIONAL INFORMATION:
    An exception occurred while executing a Transact-SQL statement or batch. (Microsoft.SqlServer.ConnectionInfo)
    The SELECT permission was denied on the object 'extended_properties', database 'mssqlsystemresource', schema 'sys'. (Microsoft SQL Server, Error: 229)
    For help, click:
    http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&ProdVer=10.50.1600&EvtSrc=MSSQLServer&EvtID=229&LinkId=20476
    Sha_woop

    Since there are so many possibilities for what might be wrong.  Here's another possibility to look at.  I ran into something where I had set up my own roles on a database.  (For instance, "Administrator", "Manager", "DataEntry", "Customer",
    each with their own kinds of limitations)  The only ones who could use it were "Manager" role or above--because they were also set up as sysadmin because they were adding users to the database (and they were highly trusted).  Also, the users that
    were being added were Windows Domain users--using their domain credentials.  (Everyone with access to the database had to be on our domain, but not everyone on the domain had access to the database--and only a few of them had access to change it.)
    Anyway, this working system suddenly stopped working and I was getting error messages similar to the above.  What I ended up doing that solved it was to go through all the permissions for the "public" role in that database and add those permissions to
    all of the roles that I had created.  I know that everyone is supposed to be in the "public" role even though you can't add them (or rather, you can "add" them, but they won't "stay added").
    So, in "SQL Server Management Studio", I went into my application's database, in other words (my localized names are obscured within <> brackets): "<Computername> (SQL Server <version> - sa)"\Databases\<MyAppDB>\Security\Roles\Database
    Roles\public".  Right-click on "public" and select "Properties".  In the "Database Role Properties - public" dialog, select the "Securables" page.  Go through the list and for each element in the list, come up with an SQL "Grant" statement to
    grant exactly that permission to another role.  So, for instance, there is a scalar function "[dbo].[fn_diagramobjects]" on which the "public" role has "Execute" privilege.  So, I added the following line:
    EXEC ( 'GRANT EXECUTE ON [dbo].[fn_diagramobjects] TO [' + @RoleName + '];' )
    Once I had done this for all the elements in the "Securables" list, I wrapped that up in a while loop on a cursor selecting through all the roles in my roles table.  This explicitly granted all the permissions of the "public" role to my database roles. 
    At that point, all my users were working again (even after I removed their "sysadmin" access--done as a temporary measure while I figured out what happened.)
    I'm sure there's a better (more elegant) way to do this by doing some kind of a query on the database objects and selecting on the public role, but after about half and hour of investigating, I wasn't figuring it out, so I just did it the brute-force method. 
    In case it helps someone else, here's my code.
    CREATE PROCEDURE [dbo].[GrantAccess]
    AS
    DECLARE @AppRoleName AS sysname
    DECLARE AppRoleCursor CURSOR LOCAL SCROLL_LOCKS FOR
    SELECT AppRoleName FROM [dbo].[RoleList];
    OPEN AppRoleCursor
    FETCH NEXT FROM AppRoleCursor INTO @AppRoleName
    WHILE @@FETCH_STATUS = 0
    BEGIN
    EXEC ( 'GRANT EXECUTE ON [dbo].[fn_diagramobjects] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT EXECUTE ON [dbo].[sp_alterdiagram] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT EXECUTE ON [dbo].[sp_creatediagram] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT EXECUTE ON [dbo].[sp_dropdiagram] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT EXECUTE ON [dbo].[sp_helpdiagramdefinition] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT EXECUTE ON [dbo].[sp_helpdiagrams] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT EXECUTE ON [dbo].[sp_renamediagram] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[all_columns] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[all_objects] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[all_parameters] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[all_sql_modules] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[all_views] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[allocation_units] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[assemblies] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[assembly_files] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[assembly_modules] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[assembly_references] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[assembly_types] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[asymmetric_keys] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[certificates] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[change_tracking_tables] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[check_constraints] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[column_type_usages] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[column_xml_schema_collection_usages] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[columns] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[computed_columns] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[conversation_endpoints] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[conversation_groups] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[conversation_priorities] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[crypt_properties] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[data_spaces] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[database_audit_specification_details] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[database_audit_specifications] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[database_files] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[database_permissions] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[database_principal_aliases] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[database_principals] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[database_role_members] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[default_constraints] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[destination_data_spaces] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[event_notifications] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[events] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[extended_procedures] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[extended_properties] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[filegroups] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[foreign_key_columns] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[foreign_keys] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[fulltext_catalogs] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[fulltext_index_catalog_usages] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[fulltext_index_columns] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[fulltext_index_fragments] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[fulltext_indexes] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[fulltext_stoplists] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[fulltext_stopwords] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[function_order_columns] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[identity_columns] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[index_columns] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[indexes] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[internal_tables] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[key_constraints] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[key_encryptions] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[message_type_xml_schema_collection_usages] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[module_assembly_usages] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[numbered_procedure_parameters] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[numbered_procedures] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[objects] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[parameter_type_usages] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[parameter_xml_schema_collection_usages] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[parameters] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[partition_functions] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[partition_parameters] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[partition_range_values] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[partition_schemes] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[partitions] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[plan_guides] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[procedures] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[remote_service_bindings] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[routes] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[schemas] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[service_contract_message_usages] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[service_contract_usages] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[service_contracts] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[service_message_types] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[service_queue_usages] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[service_queues] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[services] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[spatial_index_tessellations] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[spatial_indexes] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[sql_dependencies] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[sql_modules] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[stats] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[stats_columns] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[symmetric_keys] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[synonyms] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[syscolumns] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[syscomments] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[sysconstraints] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[sysdepends] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[sysfilegroups] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[sysfiles] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[sysforeignkeys] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[sysfulltextcatalogs] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[sysindexes] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[sysindexkeys] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[sysmembers] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[sysobjects] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[syspermissions] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[sysprotects] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[sysreferences] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[system_columns] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[system_objects] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[system_parameters] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[system_sql_modules] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[system_views] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[systypes] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[sysusers] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[table_types] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[tables] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[transmission_queue] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[trigger_events] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[triggers] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[type_assembly_usages] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[types] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[views] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[xml_indexes] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[xml_schema_attributes] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[xml_schema_collections] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[xml_schema_component_placements] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[xml_schema_components] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[xml_schema_elements] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[xml_schema_facets] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[xml_schema_model_groups] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[xml_schema_namespaces] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[xml_schema_types] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[xml_schema_wildcard_namespaces] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[xml_schema_wildcards] TO [' + @AppRoleName + '];' )
    FETCH NEXT FROM AppRoleCursor INTO @AppRoleName
    END
    CLOSE AppRoleCursor
    RETURN 0
    GO
    Once that is in the system, I just needed to "Exec GrantAccess" to make it work.  (Of course, I have a table [RoleList] which contains a "AppRoleName" field that contains the names of the database roles.)
    So, the mystery remains: why did all my users lose their "public" role and why could I not give it back to them?  Was this part of an update to SQL Server 2008 R2?  Was it because I ran another script to delete each user and add them back so to refresh
    their connection with the domain?  Well, this solves the issue for now.
    One last warning: you probably should check the "public" role on your system before running this to make sure there isn't something missing or wrong, here.  It's always possible something is different about your system.
    Hope this helps someone else.

  • Error en Query : [SQL Server] Error de Division entre 0

    Maestros !!
    Tengo este problema:
    Al ejecutar una query me figura este error " [SQL Server] Error de Division entre 0 ". Entiendo el error, cualquier numero divido por 0 arroja este problema, mi pregunta es como lo hago para no considerar las operaciones con resultado 0. Al revisar las operaciones que esta resumiendo la funcion AVG existen operaciones con resultado 0.
    La query es la siguiente:
    SELECT T3.FirmCode, T3.FirmName, SUM(T1.Quantity) as 'Cantidades', AVG(T1.Price) as 'Precio Venta Promedio', AVG(T1.StockPrice) as 'Costo Promedio', SUM(T1.LineTotal) as 'Venta Neta', AVG((1-((T1.Quantity*T1.StockPrice)/T1.LineTotal))*100) as 'Margen Almacen 01'
    INTO #FV01 FROM OINV T0  INNER JOIN INV1 T1 ON T0.DocEntry = T1.DocEntry  INNER JOIN OITM T2 ON T2.ItemCode = T1.ItemCode LEFT OUTER JOIN OMRC T3 ON T3.FirmCode = T2.FirmCode
    WHERE T0.DocDate >= '[%0]' and T0.DocDate <= '[%1]'  and ISNULL(T0.Indicator,'') <> 'NL' and T0.DocType ='I' and T1.WhsCode ='01'
    GROUP BY T3.FirmCode, T3.FirmName
    ORDER BY T3.FirmName
    SELECT T3.FirmCode, T3.FirmName, SUM(T1.Quantity) as 'Cantidades', AVG(T1.Price) as 'Precio Venta Promedio', AVG(T1.StockPrice) as 'Costo Promedio', SUM(T1.LineTotal) as 'Venta Neta', AVG((1-((T1.Quantity*T1.StockPrice)/T1.LineTotal))*100) as 'Margen Almacen 02'
    INTO #FV02 FROM OINV T0  INNER JOIN INV1 T1 ON T0.DocEntry = T1.DocEntry  INNER JOIN OITM T2 ON T2.ItemCode = T1.ItemCode LEFT OUTER JOIN OMRC T3 ON T3.FirmCode = T2.FirmCode
    WHERE T0.DocDate >= '[%0]' and T0.DocDate <= '[%1]'  and ISNULL(T0.Indicator,'') <> 'NL' and T0.DocType ='I' and T1.WhsCode ='02'
    GROUP BY T3.FirmCode, T3.FirmName
    ORDER BY T3.FirmName
    SELECT T3.FirmCode, T3.FirmName, SUM(T1.Quantity) as 'Cantidades', AVG(T1.Price) as 'Precio Venta Promedio', AVG(T1.StockPrice) as 'Costo Promedio', SUM(T1.LineTotal) as 'Venta Neta', AVG((1-((T1.Quantity*T1.StockPrice)/T1.LineTotal))*100) as 'Margen Almacen 03'
    INTO #FV03 FROM OINV T0  INNER JOIN INV1 T1 ON T0.DocEntry = T1.DocEntry  INNER JOIN OITM T2 ON T2.ItemCode = T1.ItemCode LEFT OUTER JOIN OMRC T3 ON T3.FirmCode = T2.FirmCode
    WHERE T0.DocDate >= '[%0]' and T0.DocDate <= '[%1]'  and ISNULL(T0.Indicator,'') <> 'NL' and T0.DocType ='I' and T1.WhsCode ='03'
    GROUP BY T3.FirmCode, T3.FirmName
    ORDER BY T3.FirmName
    SELECT T3.FirmCode, T3.FirmName, SUM(T1.Quantity) as 'Cantidades', AVG(T1.Price) as 'Precio Venta Promedio', AVG(T1.StockPrice) as 'Costo Promedio', SUM(T1.LineTotal) as 'Venta Neta', AVG((1-((T1.Quantity*T1.StockPrice)/T1.LineTotal))*100) as 'Margen Almacen 04'
    INTO #FV04 FROM OINV T0  INNER JOIN INV1 T1 ON T0.DocEntry = T1.DocEntry  INNER JOIN OITM T2 ON T2.ItemCode = T1.ItemCode LEFT OUTER JOIN OMRC T3 ON T3.FirmCode = T2.FirmCode
    WHERE T0.DocDate >= '[%0]' and T0.DocDate <= '[%1]'  and ISNULL(T0.Indicator,'') <> 'NL' and T0.DocType ='I' and T1.WhsCode ='04'
    GROUP BY T3.FirmCode, T3.FirmName
    ORDER BY T3.FirmName
    SELECT T3.FirmCode, T3.FirmName, SUM(T1.Quantity) as 'Cantidades', AVG(T1.Price) as 'Precio Venta Promedio', AVG(T1.StockPrice) as 'Costo Promedio', SUM(T1.LineTotal) as 'Venta Neta', AVG((1-((T1.Quantity*T1.StockPrice)/T1.LineTotal))*100) as 'Margen Almacen 05'
    INTO #FV05 FROM OINV T0  INNER JOIN INV1 T1 ON T0.DocEntry = T1.DocEntry  INNER JOIN OITM T2 ON T2.ItemCode = T1.ItemCode LEFT OUTER JOIN OMRC T3 ON T3.FirmCode = T2.FirmCode
    WHERE T0.DocDate >= '[%0]' and T0.DocDate <= '[%1]'  and ISNULL(T0.Indicator,'') <> 'NL' and T0.DocType ='I' and T1.WhsCode ='05'
    GROUP BY T3.FirmCode, T3.FirmName
    ORDER BY T3.FirmName
    SELECT T3.FirmCode, T3.FirmName, SUM(T1.Quantity) as 'Cantidades', AVG(T1.Price) as 'Precio Venta Promedio', AVG(T1.StockPrice) as 'Costo Promedio', SUM(T1.LineTotal) as 'Venta Neta', AVG((1-((T1.Quantity*T1.StockPrice)/T1.LineTotal))*100) as 'Margen Almacen 06'
    INTO #FV06 FROM OINV T0  INNER JOIN INV1 T1 ON T0.DocEntry = T1.DocEntry  INNER JOIN OITM T2 ON T2.ItemCode = T1.ItemCode LEFT OUTER JOIN OMRC T3 ON T3.FirmCode = T2.FirmCode
    WHERE T0.DocDate >= '[%0]' and T0.DocDate <= '[%1]'  and ISNULL(T0.Indicator,'') <> 'NL' and T0.DocType ='I' and T1.WhsCode ='06'
    GROUP BY T3.FirmCode, T3.FirmName
    ORDER BY T3.FirmName
    SELECT T3.FirmCode, T3.FirmName, SUM(T1.Quantity) as 'Cantidades', AVG(T1.Price) as 'Precio Venta Promedio', AVG(T1.StockPrice) as 'Costo Promedio', SUM(T1.LineTotal) as 'Venta Neta', AVG((1-((T1.Quantity*T1.StockPrice)/T1.LineTotal))*100) as 'Margen Almacen 07'
    INTO #FV07 FROM OINV T0  INNER JOIN INV1 T1 ON T0.DocEntry = T1.DocEntry  INNER JOIN OITM T2 ON T2.ItemCode = T1.ItemCode LEFT OUTER JOIN OMRC T3 ON T3.FirmCode = T2.FirmCode
    WHERE T0.DocDate >= '[%0]' and T0.DocDate <= '[%1]'  and ISNULL(T0.Indicator,'') <> 'NL' and T0.DocType ='I' and T1.WhsCode ='07'
    GROUP BY T3.FirmCode, T3.FirmName
    ORDER BY T3.FirmName
    SELECT T3.FirmCode, T3.FirmName, SUM(T1.Quantity) as 'Cantidades', AVG(T1.Price) as 'Precio Venta Promedio', AVG(T1.StockPrice) as 'Costo Promedio', SUM(T1.LineTotal) as 'Venta Neta', AVG((1-((T1.Quantity*T1.StockPrice)/T1.LineTotal))*100) as 'Margen Almacen 08'
    INTO #FV08 FROM OINV T0  INNER JOIN INV1 T1 ON T0.DocEntry = T1.DocEntry  INNER JOIN OITM T2 ON T2.ItemCode = T1.ItemCode LEFT OUTER JOIN OMRC T3 ON T3.FirmCode = T2.FirmCode
    WHERE T0.DocDate >= '[%0]' and T0.DocDate <= '[%1]'  and ISNULL(T0.Indicator,'') <> 'NL' and T0.DocType ='I' and T1.WhsCode ='08'
    GROUP BY T3.FirmCode, T3.FirmName
    ORDER BY T3.FirmName
    SELECT T3.FirmCode, T3.FirmName, SUM(T1.Quantity) as 'Cantidades', AVG(T1.Price) as 'Precio Venta Promedio', AVG(T1.StockPrice) as 'Costo Promedio', SUM(T1.LineTotal) as 'Venta Neta', AVG((1-((T1.Quantity*T1.StockPrice)/T1.LineTotal))*100) as 'Margen Almacen 09'
    INTO #FV09 FROM OINV T0  INNER JOIN INV1 T1 ON T0.DocEntry = T1.DocEntry  INNER JOIN OITM T2 ON T2.ItemCode = T1.ItemCode LEFT OUTER JOIN OMRC T3 ON T3.FirmCode = T2.FirmCode
    WHERE T0.DocDate >= '[%0]' and T0.DocDate <= '[%1]'  and ISNULL(T0.Indicator,'') <> 'NL' and T0.DocType ='I' and T1.WhsCode ='09'
    GROUP BY T3.FirmCode, T3.FirmName
    ORDER BY T3.FirmName
    SELECT T3.FirmCode, T3.FirmName, SUM(T1.Quantity) as 'Cantidades', AVG(T1.Price) as 'Precio Venta Promedio', AVG(T1.StockPrice) as 'Costo Promedio', SUM(T1.LineTotal) as 'Venta Neta', AVG((1-((T1.Quantity*T1.StockPrice)/T1.LineTotal))*100) as 'Margen Almacen 11'
    INTO #FV11 FROM OINV T0  INNER JOIN INV1 T1 ON T0.DocEntry = T1.DocEntry  INNER JOIN OITM T2 ON T2.ItemCode = T1.ItemCode LEFT OUTER JOIN OMRC T3 ON T3.FirmCode = T2.FirmCode
    WHERE T0.DocDate >= '[%0]' and T0.DocDate <= '[%1]'  and ISNULL(T0.Indicator,'') <> 'NL' and T0.DocType ='I' and T1.WhsCode ='11'
    GROUP BY T3.FirmCode, T3.FirmName
    ORDER BY T3.FirmName
    SELECT T3.FirmCode, T3.FirmName, SUM(T1.Quantity) as 'Cantidades', AVG(T1.Price) as 'Precio Venta Promedio', AVG(T1.StockPrice) as 'Costo Promedio', SUM(T1.LineTotal) as 'Venta Neta', AVG((1-((T1.Quantity*T1.StockPrice)/T1.LineTotal))*100) as 'Margen Almacen 12'
    INTO #FV12 FROM OINV T0  INNER JOIN INV1 T1 ON T0.DocEntry = T1.DocEntry  INNER JOIN OITM T2 ON T2.ItemCode = T1.ItemCode LEFT OUTER JOIN OMRC T3 ON T3.FirmCode = T2.FirmCode
    WHERE T0.DocDate >= '[%0]' and T0.DocDate <= '[%1]'  and ISNULL(T0.Indicator,'') <> 'NL' and T0.DocType ='I' and T1.WhsCode IN('12','12A','12B','12C')
    GROUP BY T3.FirmCode, T3.FirmName
    ORDER BY T3.FirmName
    SELECT T3.FirmCode, T3.FirmName, SUM(T1.Quantity) as 'Cantidades', AVG(T1.Price) as 'Precio Venta Promedio', AVG(T1.StockPrice) as 'Costo Promedio', SUM(T1.LineTotal) as 'Venta Neta', AVG((1-((T1.Quantity*T1.StockPrice)/T1.LineTotal))*100) as 'Margen Almacen 14'
    INTO #FV14 FROM OINV T0  INNER JOIN INV1 T1 ON T0.DocEntry = T1.DocEntry  INNER JOIN OITM T2 ON T2.ItemCode = T1.ItemCode LEFT OUTER JOIN OMRC T3 ON T3.FirmCode = T2.FirmCode
    WHERE T0.DocDate >= '[%0]' and T0.DocDate <= '[%1]'  and ISNULL(T0.Indicator,'') <> 'NL' and T0.DocType ='I' and T1.WhsCode ='14'
    GROUP BY T3.FirmCode, T3.FirmName
    ORDER BY T3.FirmName
    SELECT T3.FirmCode, T3.FirmName, SUM(T1.Quantity) as 'Cantidades', AVG(T1.Price) as 'Precio Venta Promedio', AVG(T1.StockPrice) as 'Costo Promedio', SUM(T1.LineTotal) as 'Venta Neta', AVG((1-((T1.Quantity*T1.StockPrice)/T1.LineTotal))*100) as 'Margen Almacen 20'
    INTO #FV20 FROM OINV T0  INNER JOIN INV1 T1 ON T0.DocEntry = T1.DocEntry  INNER JOIN OITM T2 ON T2.ItemCode = T1.ItemCode LEFT OUTER JOIN OMRC T3 ON T3.FirmCode = T2.FirmCode
    WHERE T0.DocDate >= '[%0]' and T0.DocDate <= '[%1]'  and ISNULL(T0.Indicator,'') <> 'NL' and T0.DocType ='I' and T1.WhsCode ='20'
    GROUP BY T3.FirmCode, T3.FirmName
    ORDER BY T3.FirmName
    SELECT T3.FirmCode, T3.FirmName, SUM(T1.Quantity) as 'Cantidades', AVG(T1.Price) as 'Precio Venta Promedio', AVG(T1.StockPrice) as 'Costo Promedio', SUM(T1.LineTotal) as 'Venta Neta', AVG((1-((T1.Quantity*T1.StockPrice)/T1.LineTotal))*100) as 'Margen Almacen 221'
    INTO #FV21 FROM OINV T0  INNER JOIN INV1 T1 ON T0.DocEntry = T1.DocEntry  INNER JOIN OITM T2 ON T2.ItemCode = T1.ItemCode LEFT OUTER JOIN OMRC T3 ON T3.FirmCode = T2.FirmCode
    WHERE T0.DocDate >= '[%0]' and T0.DocDate <= '[%1]'  and ISNULL(T0.Indicator,'') <> 'NL' and T0.DocType ='I' and T1.WhsCode ='221'
    GROUP BY T3.FirmCode, T3.FirmName
    ORDER BY T3.FirmName
    SELECT T3.FirmCode, T3.FirmName, SUM(T1.Quantity) as 'Cantidades', AVG(T1.Price) as 'Precio Venta Promedio', AVG(T1.StockPrice) as 'Costo Promedio', SUM(T1.LineTotal) as 'Venta Neta', AVG((1-((T1.Quantity*T1.StockPrice)/T1.LineTotal))*100) as 'Margen Almacen 22'
    INTO #FV22 FROM OINV T0  INNER JOIN INV1 T1 ON T0.DocEntry = T1.DocEntry  INNER JOIN OITM T2 ON T2.ItemCode = T1.ItemCode LEFT OUTER JOIN OMRC T3 ON T3.FirmCode = T2.FirmCode
    WHERE T0.DocDate >= '[%0]' and T0.DocDate <= '[%1]'  and ISNULL(T0.Indicator,'') <> 'NL' and T0.DocType ='I' and T1.WhsCode ='22'
    GROUP BY T3.FirmCode, T3.FirmName
    ORDER BY T3.FirmName
    SELECT T3.FirmCode, T3.FirmName, SUM(T1.Quantity) as 'Cantidades', AVG(T1.Price) as 'Precio Venta Promedio', AVG(T1.StockPrice) as 'Costo Promedio', SUM(T1.LineTotal) as 'Venta Neta', AVG((1-((T1.Quantity*T1.StockPrice)/T1.LineTotal))*100) as 'Margen Almacen 23'
    INTO #FV23 FROM OINV T0  INNER JOIN INV1 T1 ON T0.DocEntry = T1.DocEntry  INNER JOIN OITM T2 ON T2.ItemCode = T1.ItemCode LEFT OUTER JOIN OMRC T3 ON T3.FirmCode = T2.FirmCode
    WHERE T0.DocDate >= '[%0]' and T0.DocDate <= '[%1]'  and ISNULL(T0.Indicator,'') <> 'NL' and T0.DocType ='I' and T1.WhsCode ='23'
    GROUP BY T3.FirmCode, T3.FirmName
    ORDER BY T3.FirmName
    ---SELECCION DE DATOS
    SELECT T3.FirmCode, T3.FirmName as 'Proveedor',
    (Select T201.[Margen Almacen 01] From  #FV01 T201 where T201.[FirmCode] = T3.FirmCode) as 'Margen Venta Local 01',
    (Select T202.[Margen Almacen 02] From  #FV02 T202 where T202.[FirmCode] = T3.FirmCode) as 'Margen Venta Local 02',
    (Select T203.[Margen Almacen 03] From  #FV03 T203 where T203.[FirmCode] = T3.FirmCode) as 'Margen Venta Local 03',
    (Select T204.[Margen Almacen 04] From  #FV04 T204 where T204.[FirmCode] = T3.FirmCode) as 'Margen Venta Local 04',
    (Select T205.[Margen Almacen 05] From  #FV05 T205 where T205.[FirmCode] = T3.FirmCode) as 'Margen Venta Local 05',
    (Select T206.[Margen Almacen 06] From  #FV06 T206 where T206.[FirmCode] = T3.FirmCode) as 'Margen Venta Local 06',
    (Select T207.[Margen Almacen 07] From  #FV07 T207 where T207.[FirmCode] = T3.FirmCode) as 'Margen Venta Local 07',
    (Select T208.[Margen Almacen 08] From  #FV08 T208 where T208.[FirmCode] = T3.FirmCode) as 'Margen Venta Local 08',
    (Select T209.[Margen Almacen 09] From  #FV09 T209 where T209.[FirmCode] = T3.FirmCode) as 'Margen Venta Local 09',
    (Select T211.[Margen Almacen 11] From  #FV11 T211 where T211.[FirmCode] = T3.FirmCode) as 'Margen Venta Local 11',
    (Select T212.[Margen Almacen 12] From  #FV12 T212 where T212.[FirmCode] = T3.FirmCode) as 'Margen Venta Local 12',
    (Select T214.[Margen Almacen 14] From  #FV14 T214 where T214.[FirmCode] = T3.FirmCode) as 'Margen Venta Local 14',
    (Select T220.[Margen Almacen 20] From  #FV20 T220 where T220.[FirmCode] = T3.FirmCode) as 'Margen Venta Local 20',
    (Select T221.[Margen Almacen 221] From  #FV21 T221 where T221.[FirmCode] = T3.FirmCode) as 'Margen Venta Local 221',
    (Select T222.[Margen Almacen 22] From  #FV22 T222 where T222.[FirmCode] = T3.FirmCode) as 'Margen Venta Local 22',
    (Select T223.[Margen Almacen 23] From  #FV23 T223 where T223.[FirmCode] = T3.FirmCode) as 'Margen Venta Local 23'
    INTO #RESULT FROM OITM T2 LEFT OUTER JOIN OMRC T3 ON T3.FirmCode =T2.FirmCode
    GROUP BY T3.FirmCode, T3.FirmName
    ORDER BY T3.FirmName
    SELECT * FROM #RESULT where isnull([Margen Venta Local 01],0) <> 0
    or isnull([Margen Venta Local 02], 0) <> 0
    or isnull([Margen Venta Local 03], 0) <> 0
    or isnull([Margen Venta Local 04], 0) <> 0
    or isnull([Margen Venta Local 05], 0) <> 0
    or isnull([Margen Venta Local 06], 0) <> 0
    or isnull([Margen Venta Local 07], 0) <> 0
    or isnull([Margen Venta Local 08], 0) <> 0
    or isnull([Margen Venta Local 09], 0) <> 0
    or isnull([Margen Venta Local 11], 0) <> 0
    or isnull([Margen Venta Local 12], 0) <> 0
    or isnull([Margen Venta Local 14], 0) <> 0
    or isnull([Margen Venta Local 20], 0) <> 0
    or isnull([Margen Venta Local 221], 0) <> 0
    or isnull([Margen Venta Local 22], 0) <> 0
    or isnull([Margen Venta Local 23], 0) <> 0
    ---FIN
    Agradeciendo vuestra ayuda.

    Buenas Tardes Eloy
    Al revisar todas las transacciones una a una, ninguna de ellas en el campo T1.LineTotal tiene como resultado el valor 0 ya que el campo T1.LineTotal es el monto neto de la venta (sin impuestos) y este nunca es 0 ya que tenemos validaciones antes de crear el documento.
    El valor 0 aparece como resultado de esta operación ((1-((T1.Quantity*T1.StockPrice)/T1.LineTotal))*100), ya que en varios ventas se vendió al mismo precio del costo del producto debido a promociones o liquidaciones de stock, por lo tanto el resultado 0 en dicha operación es correcto.
    Cuando a estas operación le aplico la función AVG para resumir datos comienza el problema.
    Que me sugieres que realice?
    Agradeciendo tu ayuda.

  • How to fix Login failed for user ''. (Microsoft SQL Server, Error: 18456)in windows 2008?

    Hi All,
    we are facing the Login fails issue .
    how to resolve the bellow error , could you please suggested the possible ways .. ASAP
    TITLE: Connect to Server
    Cannot connect to ..
    ADDITIONAL INFORMATION:
    Login failed for user '  domain\name'. (Microsoft SQL Server, Error: 18456)
    For help, click: http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&EvtSrc=MSSQLServer&EvtID=18456&LinkId=20476
    BUTTONS:
    OK
    Log Name:      Application
    Source:        MSSQLSERVER
    Date:          10/6/2011 1:56:28 PM
    Event ID:      18456
    Task Category: Logon
    Level:         Information
    Keywords:      Classic,Audit Failure
    User:          domain\name
    Computer:      
    Description:
    Login failed for user '  domain\name'. Reason: Token-based server access validation failed with an infrastructure error. Check for previous errors. [CLIENT: <local machine>]
    RAM

    I was hitting myself in the head with this problem for a couple of minutes.... Everything was fine on the DC and Domain itself.. I added the Domain admins Group Principal for which I am part of... I was getting this error  ... Long History... Short
     (Right Click and Run as Administrator took care of this for me..) UAC was the cause of the problem.
    Cannot connect to XX-DB-XX3.
    ===================================
    Login failed for user 'XXXXS\XXas'. (.Net SqlClient Data Provider)
    For help, click: http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&EvtSrc=MSSQLServer&EvtID=18456&LinkId=20476
    Server Name: XX-DB-XX3
    Error Number: 18456
    Severity: 14
    State: 1
    Line Number: 65536
    Program Location:
       at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)
       at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj)
       at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)
       at System.Data.SqlClient.SqlInternalConnectionTds.CompleteLogin(Boolean enlistOK)
       at System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, Boolean ignoreSniOpenTimeout, Int64 timerExpire, SqlConnection owningObject)
       at System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(String host, String newPassword, Boolean redirectedUserInstance, SqlConnection owningObject, SqlConnectionString connectionOptions, Int64 timerStart)
       at System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(SqlConnection owningObject, SqlConnectionString connectionOptions, String newPassword, Boolean redirectedUserInstance)
       at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, Object providerInfo, String newPassword, SqlConnection owningObject, Boolean redirectedUserInstance)
       at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection)
       at System.Data.ProviderBase.DbConnectionFactory.CreateNonPooledConnection(DbConnection owningConnection, DbConnectionPoolGroup poolGroup)
       at System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection)
       at System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory)
       at System.Data.SqlClient.SqlConnection.Open()
       at Microsoft.SqlServer.Management.SqlStudio.Explorer.ObjectExplorerService.ValidateConnection(UIConnectionInfo ci, IServerType server)
       at Microsoft.SqlServer.Management.UI.ConnectionDlg.Connector.ConnectionThreadUser()

  • MS SQL 2008 R2 Named instance: Login failed. Microsoft SQL server, Error: 18452) - Tryig to access using the FQDN assigned for the backup network card.

    Hi,
       I have a windows 2008 R2 Enterprise servers with standalone MS-SQL 2008 R2 named instance.  The server is having two networks, once production and the second for backup. The server FQDN is resolving to the production IP. The backup NIC
    DNS dynamic update is disabled and an "A" record is registered with the dns.  While trying to connect to the instance using the management studio:
    Successfuly able to connect using the instance name, the production hostname, production IP and backup IP. 
    but while trying to connect to the insance using the backup hostname getting the below error:
    "Login failed. The login is an untrusted domain and cannot be used with windows authentication. (Microsoft SQL server, Error: 18452) "
    This is required for the backup tool to get connected using the backup FQDN of the server.
    Should I need to create a host name alias,  request you to kindly assist me with the best recommedation to fix this.
    http://blogs.msdn.com/b/dbrowne/archive/2012/05/21/how-to-add-a-hostname-alias-for-a-sql-server-instance.aspx

    Hi,
    It might be a kerberos issue.  Check that there are valid SPN's registered using the setspn utility - http://technet.microsoft.com/en-us/library/cc731241.aspx
    Thanks, Andrew
    My blog...

  • I am geeting problem whem i run bulk insert query i got error Location:_ bcpimp.cpp:1797 Expression:_ cbOutTemp cbOutputStr SPID:__ 52 Process ID:_ 2364 Msg 3624, Level 20, State 1, Line 3 A system assertion check has failed. Check the SQL Server error

    Location: bcpimp.cpp:1797
    Expression: cbOutTemp < cbOutputStr
    SPID: 52
    Process ID: 2364
    Msg 3624, Level 20, State 1, Line 3
    A system assertion check has failed. Check the SQL Server error log for details. Typically, an assertion failure is caused by a software bug or data corruption. To check for database corruption, consider running DBCC CHECKDB. If you agreed to send dumps to
    Microsoft during setup, a mini dump will be sent to Microsoft. An update might be available from Microsoft in the latest Service Pack or in a QFE from Technical Support. 
    Msg 0, Level 20, State 0, Line 0
    A severe error occurred on the current command.  The results, if any, should be discarded.

    If you check your sql server error log folder you will see dump files created. You need to send those dump files to Microsoft for inspection because outside of microsoft product support the symbols for reading the dumps are not available without which it
    wont be easy to find the issue.
    http://support.microsoft.com/kb/2028589
    In the meantime check if you are on the latest version of Service Pack and if not apply the latest service pack. Majority of these kind of assertions are bugs which are solved in Service Packs/Cumulative Updates.
    Regards, Ashwin Menon My Blog - http:\\sqllearnings.com

  • SQl Server Error:927 and Restoring

    i have a problem with sharepoint database in SQL 2005.
    status of tow database in sql studio mamagment are restoring...
    how can i stop that? (change status to normal)
    AND SO :
    WHEN I GET A PROPERTISE OF THOSE DATABASE THIS ERROR APEAR:
    database cannot be openned. it is  in middle of restore. microsoft SQL server Error:927

    Hi Tibor,
    I am getting same error but here database is set to standby mode(logshipped), suggestion please..
    Error:
    database cannot be openned. it is  in middle of
    restore. microsoft SQL server Error:927
    TARAK
    Hi Tarak,
    Did the restore complete? If there are no further backups to be restored then try below command
    RESTORE DATABASE <name_here> WITH RECOVERY
    Balmukund Lakhani | Please mark solved if I've answered your question, vote for it as helpful to help other users find a solution quicker
    This posting is provided "AS IS" with no warranties, and confers no rights.
    My Blog |
    Team Blog | @Twitter
    Author: SQL Server 2012 AlwaysOn -
    Paperback, Kindle

  • SQL Server Error 4145

    Hi,
    I have a stored procedure with the code below that is behaving strangely. 
    I'm using
    SQL Server 2008 R2 with Visual Studio 2010 When I open SQL within Visual Studio and insert the query below, and I click the "Verify SQL Syntax" button, I get two messages.: 
    1st - The SQL syntax has been verified against data source. 
    2nd - The Following Errors were encountered while parsing the contents of the SQL pane: 
    The OVER SQL construct or statement is not supported. 
    How do I fix this error?
    I run in the Visual Studio 2010 IDE and the result is displayed without errors. 
    The first time I run the web page that consumes the stored procedure, sometimes the result is displayed, also without error. 
    The second time on, I always get the message SQL Server Error 4145. 
    Can anyone help me?
    SELECT *
    FROM (
    SELECT ROW_NUMBER() OVER (ORDER BY Livros.LivroTitulo ASC) AS row,
    Livros.LivroId,
    Livros.LivroLojistaId,
    Livros.LivroStatusId,
    Livros.LivroMarcaId,
    Livros.LivroAutorId,
    Livros.LivroTitulo,
    Livros.LivroSubtitulo,
    Livros.LivroISBN13,
    Livros.LivroEAN13,
    Livros.LivroIdiomaId,
    Livros.LivroEstadoId,
    Livros.LivroAcabamentoId,
    Livros.LivroNumeroEdicao,
    Livros.LivroAnoPublicacao,
    Livros.LivroNumeroPaginas,
    Livros.LivroPrecoCusto,
    Livros.LivroPrecoCapa,
    Livros.LivroAliquotaIPI,
    Livros.LivroAliquotaICMS,
    Livros.LivroPeso,
    Livros.LivroAltura,
    Livros.LivroLargura,
    Livros.LivroImagemCapa,
    Livros.LivroResenha, 
    Livros.LivroCriadoPorUsuarioId,
    Livros.LivroDataCadastro,
    Marcas.MarcaNome AS Editora,
    LivrosAutores.LivroAutorLivroId,
    Autores.AutorId,
    Autores.AutorNome AS Autor
    FROM Livros
    INNER JOIN Marcas ON Marcas.MarcaId = Livros.LivroMarcaId
    INNER JOIN LivrosAutores ON LivrosAutores.LivroAutorLivroId = Livros.LivroId AND LivrosAutores.LivroAutorAutorId = Livros.LivroAutorId 
    INNER JOIN Autores ON Autores.AutorId = LivrosAutores.LivroAutorAutorId
    WHERE 
    Livros.LivroTitulo LIKE 'só%') AS Tabela

    SQL Database Recovery software is the best and powerful software. This software repair damaged or corrupt SQL databases. The software can repair both the MDF and NDF SQL database files. For more information and free download click http://sqldatabserecovery.weebly.com/
    and http://sqldatabserecovery.weebly.com/recovery-for-sql.html

  • SQL server error log size is too big to handle

    I am working with a large database on windows sql server 2008 R2 such that it has to run continuously 24x7 because of that it is not possible
    to restart the server time to time. It is kind of monitoring system for big machines. Because of this SQL server error logs are growing too big even some times up to 60-70 GB at a limited sized hard drive. I can't delete them time to time manually. Can someone
    please suggest a way using which I can stop creation of such error logs or recycle them after sometime. Most of the errors are of this kind --
    Setting database option RECOVERY to simple for database db_name
    P.S.- I have read limiting error logs to 6 etc. But that didn't help. It will be best if you could suggest some method to disable these logs.

    Hi Mohit11,
    According to your description, your SQL Server error logs are growing too big to handle at a limited sized hard drive, and you want to know how to stop the generation of such error logs or recycle them after sometime automatically without restarting the
    SQL Server, right?
    As others mentioned above, we may not be able to disable SQL server error log generation. However we can recycle the error logs automatically by running the
    sp_cycle_errorlog on a fixed schedule (i.e. every two weeks) using SQL agent jobs so that the error logs will be recycled
    automatically without restarting SQL Server.
    And it is also very important for us to keep the error log files more readable. So we can increase the number of error logs a little more and run the sp_cycle_errorlog more frequently (i.e. daily), then each file will in a smaller size to be more readable
    and we can recycle the log files automatically.
    In addition, in order to avoid the size of all the log files growing into a too big size unexpected (sometime it may happen), we can run the following query in SQL Agent job to automatically delete all the old log files when the size of log files is larger
    than some value we want to keep (i.e. 30GB):
    --create a tample table to gather the information of error log files
    CREATE TABLE #ErrorLog
    Archieve INT,
    Dt DATETIME,
    FileSize INT
    GO
    INSERT INTO #ErrorLog
    EXEC xp_enumerrorlogs
    GO
    --delete all the old log files if the size of all the log files is larger than 30GB
    DECLARE @i int = 1;
    DECLARE @Log_number int;
    DECLARE @Log_Max_Size int = 30*1024; --here is the max size (M) of all the error log files we want to keep, change the value according to your requirement
    DECLARE @SQLSTR VARCHAR(1000);
    SET @Log_number = (SELECT COUNT(*) FROM #ErrorLog);
    IF (SELECT COUNT(FileSize/1024/1024) FROM #ErrorLog) >= @Log_Max_Size
    BEGIN
    WHILE @i <= @Log_number
    BEGIN
    SET @SQLSTR = 'DEL C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\Log\ERRORLOG.' + CONVERT(VARCHAR,@i);
    EXEC xp_cmdshell @SQLSTR;
    SET @i =@i + 1;
    END
    END
    DROP TABLE #ErrorLog
    For more information about How to manage the SQL Server error log, please refer to the following article:
    http://support.microsoft.com/kb/2199578
    If you have any question, please feel free to let me know.
    Regards,
    Jerry Li

  • HI Connection failed: SQLState: '08001' SQL Server Error:

    Hi all,
    my server in workgroup and all client pc in domain is any cooneting issue
    Operating server   - Window Server 2008
    Database - Sql server 2005
    SAP - sap 2007B pl 08
    but when i connect client to the server i getting error:
    Connection failed: SQLState: '08001' SQL Server Error: 17 [DBNETLIB][ConnectionOpen (Connect()).]SQL Server does not exist or access denied.
    so please tell me if any setting that will change to established coonetion.
    Regards \
    Raj

    Please check if the named pipes and tcp/ip are enabled in client protocols and protocols for ms-sql server. You can do so by going to sql server configuration manager.
    Rahul

  • Can't connect to the database after 1-2 day, Named Pipes Provider, error: 40,Microsoft SQL Server, Error: 121

    HI
    I have a problem. I can't connect to the database. It said : 
    An error has occurred while establishing a connection to the server.  When connecting to SQL Server 2005, this failure may be caused by the fact that under the default settings SQL Server does not allow remote connections. (provider: Named Pipes Provider,
    error: 40 - Could not open a connection to SQL Server) (Microsoft SQL Server, Error: 121)
    When I restart the server, I can connect normally. But after 1-2 days, it can't be connected. 
    How can I fix this?

    Hi Lee,
    Please refer to the following article to configure SQL Server 2005 to allow remote connections:
    http://support.microsoft.com/kb/914277/en-us
    Regards,
    Elvis Long
    TechNet Community Support

  • MS Sql Server Error 1418

    Hi,
    As I am going to configure Database Mirroring in sql server 2008 R2. It is giving error 1418.
    The server network address "TCP://xyzserver.domain.con:5022" can not reached or does not exist. Check network address name and that the ports for the local and remote endpoints sre operational.(Microsoft SQL Server, Error: 1418)
    I have tried the below steps:
    1. ALTER ENDPOINT Mirroring FOR DATA_MIRRORING (ROLE = PARTNER, ENCRYPTION = SUPPORTED)
    2. ALTER DATABASE PROD_DB SET PARTNER = 'TCP://xyzserver.domain.Com:5022'
    3. DROP ENDPOINT Mirroring
    SELECT *
    FROM sys.endpoints
    4. CREATE ENDPOINT Mirroring
        STATE = STARTED
        AS TCP ( LISTENER_PORT = 60801 )
        FOR DATABASE_MIRRORING (
           AUTHENTICATION = WINDOWS KERBEROS,
           ENCRYPTION = SUPPORTED,
           ROLE=ALL);
    SELECT state ,state_desc FROM sys.database_mirroring_endpoints 
    3. GRANT CONNECT ON ENDPOINT::Mirroring TO ALL
    4. GRANT CONNECT ON ENDPOINT::Mirroring TO SA
        WITH GRANT OPTION;
    GO
    I have tried all above the steps. But still I can not resolve the issue.
    Can anyboby help me?
    Sachin Jain

    Please check below points
    Make sure that the mirror database is ready for mirroring.
    Make sure that the name and port of the mirror server instance are correct.
    Make sure that the destination mirror server instance is not behind a firewall.
    Make sure that the principal server instance is not behind a firewall.
    Verify that the endpoints are started on the partners by using the state or state_desc column the of the sys.database_mirroring_endpoints catalog view. If either endpoint is not started, execute an ALTER ENDPOINT statement to start it.
    To identify the listening ports and the processes that have those ports opened, follow these steps:
    Obtain the process ID.
    To learn the process ID of an instance of SQL Server, connect to that instance and use the following Transact-SQL statement:
     SELECT SERVERPROPERTY('ProcessID') 
    Match the process ID with the output of the following netstat command:
    netstat -ano
    also please check local host file are set-up correctly ipaddress and hostnames for (principal, mirror and witness)
    http://uk.linkedin.com/in/ramjaddu

Maybe you are looking for