Ads

04 April 2025

Grant select access to specific object or tables

 We can grant select access to specific Tables / Objects in three ways 

Create Login on SQL server instance 








In my case Login name Appteam






Don't Grant any server role to Login









I need fetch data from TEST_Mirr database 

Don't grant any database role

Default public will be there 








On Database user will be created automatically 











Here for Appteam not showing any tables on the TEST_Mirr database 











1) using T SQL 

Granted select on below two tables for Appteam user

use TEST_Mirr 

Grant select on conn1 to Appteam

Grant select on conn2 to Appteam



2) Using GUI 

Using Admin session go to user properties 









Click on search and select all objects of the types and click ok , it will pop up new dialog box









Select Tables and click OK








This time i am going grant select access on Output_Field table 









After granting select permissions on Output_Field table










3) Using Table Properties 

For which we need to grand select on the table go to that table properties









Go to permissions tab >>> search for a user >>> grant select as shown in below screenshots 
















Now we can see all the tables which we granted select access



09 December 2024

The feature “Scale-out deployment” is not supported in this edition of Reporting Services


Step1 :Connect to SSMS

Step2: Open New query window 

Step3: run below query

Use Report server

go

Select * from Keys


Step4: List all the keys that needs to be deleted, except the NULL one. 

Note: Don't delete NULL this is current one.


Step5:  Execute below command

Delete from Keys where instalationID=<>

Step 6: Restart SSRS 






















27 October 2024

SQL Server Performance issue - With DB Compatibility upgrade from 120 to 150

Worked Solution:

We turned on the Legacy Cardinality Estimation on the database properties. 

If anyone has other solutions please comment.


24 January 2024

SQL Server 2022 Services Failed To Come Online.

Error: Script level upgrade for database ‘master’ failed because upgrade step msdb110_upgrade.sql encountered error 926, state 1, severity 25


The above error will be present in the Error log and the solution will be to start the SQL Server either from /T902 or add this in strtup parameter to permently resolve this issue. 

This will bypass the upgrade script and starts the SQL Server. 


Reference:

https://blog.sqlauthority.com/2019/04/04/sql-server-script-level-upgrade-for-database-master-failed-because-upgrade-step-msdb110_upgrade-sql-encountered-error-8649-state-1-severity-17/


17 December 2023

Failed to initialize sqlcmd library with error number -2147467259.

This error has too many options to fix, one of them is below resolution - 

In our case we were using a dynamic query which will send some results over the email with help of dynamic execution. when the query was executed using sp_send_mail it used to fail.

Failed to initialize sqlcmd library with error number -2147467259.

After couple of hours identified that query results using linked server was causing the issue. 

An error occurred during Service Master Key decryption There is no remote user ' ' mapped to local user '(null)' from the remote server ' '. (Microsoft SQL Server, Error: 33094)

To fix this we need to run 

        ALTER SERVICE MASTER KEY FORCE REGENERATE

Once the above command executed linked server started working properly. The dynamic query started to work smoothly, which inturn resolved the issue. 



22 November 2023

SSRS not starting - unable to connect to the report server

 After the windows upgrade few cases WMI RS integration will be corrupted, during that time we get the error "Unable to connect to the Report Server "




Solution : 

Based on the SQL Server Version the MOF file will be located in different locations, in our case it was on D drive.

1. Open CMD prompt with elevated privileges

2. Run below command 


mofcomp "D:\SQL Server Files\MSRS13.MSSQLSERVER\Reporting Services\ReportServer\bin\\reportingservices.mof"


=============== This will fix the issue =================



26 April 2023

SQL Server DB Object, Job and DB Owner Details

 -- Below will provide the Job Owner Details

SELECT s.name AS JobName, l.name AS JobOwner, s.enabled

FROM msdb..sysjobs s

LEFT JOIN master.sys.syslogins l ON s.owner_sid = l.sid

WHERE l.name IS NOT NULL and l.name in ('Domain\User' )

ORDER by l.name

 

-- Below will provide DB Owners

SELECT name,

        suser_sname( owner_sid ) AS DBOwnerName

FROM master.sys.databases

WHERE suser_sname( owner_sid )in  ('Domain\User' )

 

--- Below will provide Each Object Owners 

;with objects_cte as

(

    select

        o.name,

        o.type_desc,

        case

            when o.principal_id is null then s.principal_id

            else o.principal_id

        end as principal_id

    from sys.objects o

    inner join sys.schemas s

    on o.schema_id = s.schema_id

    where o.is_ms_shipped = 0

    and o.type in ('U', 'FN', 'FS', 'FT', 'IF', 'P', 'PC', 'TA', 'TF', 'TR', 'V')

)

select

    cte.name,

    cte.type_desc,

    dp.name

from objects_cte cte

inner join sys.database_principals dp

on cte.principal_id = dp.principal_id

where dp.name in  ('Domain\User' ) or dp.name <>'dbo'

 

07 November 2022

Restore encrypted databases

 Msg 33111, Level 16, State 3, Line 1

Cannot find server certificate with thumbprint '0xE11A199C1059C6F1E0223B56581CDCF3F043DFE8'.
Msg 3013, Level 16, State 1, Line 1
RESTORE DATABASE is terminating abnormally.


02 November 2022

Script to List the Version and Edition

 SELECT

   SERVERPROPERTY ('MachineName') AS PhysicalMachineName,

   SERVERPROPERTY ('ServerName') AS SQLServerName,

   SERVERPROPERTY ('Edition') AS ServerEdition,

     CASE 

     WHEN CONVERT(VARCHAR(128), SERVERPROPERTY ('productversion')) like '8%' THEN 'SQL2000'

     WHEN CONVERT(VARCHAR(128), SERVERPROPERTY ('productversion')) like '9%' THEN 'SQL2005'

     WHEN CONVERT(VARCHAR(128), SERVERPROPERTY ('productversion')) like '10.0%' THEN 'SQL2008'

     WHEN CONVERT(VARCHAR(128), SERVERPROPERTY ('productversion')) like '10.5%' THEN 'SQL2008 R2'

     WHEN CONVERT(VARCHAR(128), SERVERPROPERTY ('productversion')) like '11%' THEN 'SQL2012'

     WHEN CONVERT(VARCHAR(128), SERVERPROPERTY ('productversion')) like '12%' THEN 'SQL2014'

     WHEN CONVERT(VARCHAR(128), SERVERPROPERTY ('productversion')) like '13%' THEN 'SQL2016'     

     WHEN CONVERT(VARCHAR(128), SERVERPROPERTY ('productversion')) like '14%' THEN 'SQL2017' 

     WHEN CONVERT(VARCHAR(128), SERVERPROPERTY ('productversion')) like '15%' THEN 'SQL2019' 

     ELSE 'unknown'

  END AS MajorVersion,

   CASE 

     WHEN CONVERT(VARCHAR(128), SERVERPROPERTY ('productversion')) like '8%' THEN SERVERPROPERTY ('productlevel') 

     WHEN CONVERT(VARCHAR(128), SERVERPROPERTY ('productversion')) like '9%' THEN SERVERPROPERTY ('productlevel') 

     WHEN CONVERT(VARCHAR(128), SERVERPROPERTY ('productversion')) like '10.0%' THEN SERVERPROPERTY ('productlevel') 

     WHEN CONVERT(VARCHAR(128), SERVERPROPERTY ('productversion')) like '10.5%' THEN SERVERPROPERTY ('productlevel')  

     WHEN CONVERT(VARCHAR(128), SERVERPROPERTY ('productversion')) like '11%' THEN SERVERPROPERTY ('productlevel')  

     WHEN CONVERT(VARCHAR(128), SERVERPROPERTY ('productversion')) like '12%' THEN SERVERPROPERTY ('productlevel') 

     WHEN CONVERT(VARCHAR(128), SERVERPROPERTY ('productversion')) like '13%' THEN SERVERPROPERTY ('productlevel')  

        

else

SERVERPROPERTY('ProductUpdateLevel')

END  as 'ProductUpdate Level',


  SERVERPROPERTY ('ProductVersion')  AS ProductVersion,

    --RIGHT(@@version, (Len(@@Version)-charindex('Windows',@@version, 1))+1) AS [O.S.],

 SERVERPROPERTY ('Collation') AS Collation


25 February 2022

Query to list the SPID time and completion time

 Here is the query i found on one of the blogs, we can use this to know the SPID duration along with wait type. Thanks to the blogger.

===================================================================

SELECT R.session_id

, R.percent_complete

, R.total_elapsed_time/1000 AS elapsed_seconds

, R.wait_type

, R.wait_time

, R.last_wait_type

, DATEADD(s,100/((R.percent_complete)/ (R.total_elapsed_time/1000)), R.start_time) AS est_complete_time

, ST.text AS batch_text


, CAST(SUBSTRING(ST.text, R.statement_start_offset / 2, 

(

CASE WHEN R.statement_end_offset = -1 THEN DATALENGTH(ST.text)

ELSE R.statement_end_offset

END - R.statement_start_offset 

) / 2 

) AS varchar(1024)) AS statement_executing

FROM sys.dm_exec_requests AS R

CROSS APPLY sys.dm_exec_sql_text(R.sql_handle) AS ST

WHERE R.percent_complete > 0

AND R.session_id <> @@spid;

=====================================================================

03 August 2021

SSIS- The version number in the package is not valid.

Package migration from version 8 to version 6 failed with error 0xC001700A "The version number in the package is not valid. The version number cannot be greater than current version number.". 

Solution:

1. Go to properties 

2. Change the Version and redeploy the package


3. Copy the DTSX or move it to source server and execute.



27 July 2021

Alter failed for Database 'DBNAME '. (Microsoft.SqlServer.Smo), It is in the middle of a restore. (Microsoft SQL Server, Error: 927)

 First Solution 

This error will appear when we configure DB Mirroring. 

Solution 1:

Please ensure you restored the latest log backup on the mirrored server and then click on start mirroring again on principal.
 
Solution 2:
 
Set the endpoints on both mirror and principal servers by executing the below commands on each server.

On Mirror Server:
 
 ALTER DATABASE DBNAME SET PARTNER = ‘TCP://PrincipalServername.com:5022’

On Principal Server:
 
 ALTER DATABASE DBNAEM SET PARTNER = ‘TCP://MirrorServername.com:5022’

01 April 2021

The publisher of this content does not allow it to be displayed in a frame

This will issue will come when SQL Server has been upgraded to any versions after 2016, SSRS reports that are used to display in iFrame will fail to display.



Solution:

Go to URL and change the URL to reportviwer, if the URL is using reports then it will not dispay in the iframe.

Example:

Change From:

https://Server/Reports/browse

Change To:

https://Server/ReportServer/Pages/ReportViewer.aspx?&rs:embed=true

or

 http://Servername/ReportServer/Pages/ReportViewer.aspx?%kjhkjs%khjkhkjhy%retre+uytts%2popiopoi+iuiuyiuy&rs:Command=Render&Rs:embed=true


Note:  this will be your report name -> %kjhkjs%khjkhkjhy%retre+uytts%2popiopoi+iuiuyiuy


23 December 2020

SSRS Failed to Start - an error occurred when attempting to connect to the report server remote procedure call (RPC) end point.

ERROR: 

report server remote procedure call (RPC) end point. Verify that the Report Server Windows service is running, and then retry the operation.

 ---> System.Runtime.InteropServices.COMException: The RPC server is not listening. (Exception from HRESULT: 0x800706B3)

   --- End of inner exception stack trace ---

   at Microsoft.ReportingServices.WmiProvider.RSWmiAdmin.ThrowOnError(ManagementBaseObject mo)

   at Microsoft.ReportingServices.WmiProvider.RSWmiAdmin.GenerateDatabaseScript(String databaseName, Int32 lcid, Boolean isSharePointIntegrated, String& script)

   at ReportServicesConfigUI.WMIProvider.RSReportServerAdmin.GenerateDatabaseScript(String databaseName, Int32 lcid, Boolean isSharePointIntegrated, String& script)


Solution:

1. Switch the account to local service/local system

2. Start the reporting services and configure.

3. Now change the service account to domain account.

 

29 November 2020

SQL Server Job - Failing - Error: 4014, Severity: 20, State: 8.

 There are many reasons to fail the SQL Server job with this error code like -

        1. Permission issue for the Job owner
        2. Permissions for the SQL Server Agent account
        3. Permissions on MSDB and User Datbases
        4. Issues with the sp_send_dbmail parameters 
If above are proper please follow the below steps to identify the issue -

Open profiler and choose the below events and then run the job.



In our case this was the culprit.



Now fix the code and run the job, which will succeed. 


29 October 2020

Job Output file location

-- Script to find the JobOutPut Location.

select j.name,js.output_file_name,

  js.step_name,js.database_name "Executing On which DB?",

  last_run_outcome = case when js.last_run_outcome = 0 then 'Failed'

        when js.last_run_outcome = 1 then 'Succeeded'

        when js.last_run_outcome = 2 then 'Retry'

        when js.last_run_outcome = 3 then 'Canceled'

        else 'Unknown'

       end,

  last_run_datetime = msdb.dbo.agent_datetime(

       case when js.last_run_date = 0 then NULL else js.last_run_date end,

       case when js.last_run_time = 0 then NULL else js.last_run_time end)

from msdb.dbo.sysjobs j

  inner join msdb.dbo.sysjobsteps js

   on j.job_id = js.job_id

   WHERE js.output_file_name <> '[NULL]' 

  order by js.output_file_name



Thanks to : https://www.sqlservercentral.com/scripts/query-to-find-the-job-output-file-location-at-each-job-step

28 July 2020

Change Mode Of SSAS


Below are the details how we can change this mode, please note take a backup of existing CUBES before changing this option.

DeploymentModes :

DeploymentMode=2 for Tabular Mode
DeploymentMode=0 for Multidimensional Mode
DeploymentMode=1 is for PowerPivot for SharePoint instances.

Steps:

  1. Backup any multidimensional databases on the server and either detach them or delete them.  Once mode is changed this may not work.
  2. Copy the msmdsrv.ini file to safe location this can be found here - C:\Program Files\Microsoft SQL Server\MSAS15.MSSQLSERVER\OLAP\Config.
  3. Open the config file in Notepad. Change the DeploymentMode property as required - 0 (multidimensional) to 2 (tabular) Save and close the file.
  4. Copy the msmdsrv.ini file back to the OLAP\Config directory.
  5. Restart the SQL Server Analysis Services instance.

18 May 2020

SQL Server Agent Not Coming OnLine After Reboot

This issue occurred recently whenever the server was rebooted SQL Server Agent was not coming online. Noticed the below error message in event viewr.

"The SQL Server Agent service failed to start due to the following error:
The service did not respond to the start or control request in a timely fashion."

Resolution As follows:

https://support.microsoft.com/en-in/help/922918/a-service-does-not-start-and-events-7000-and-7011-are-logged-in-window

  1. Click Start, click Run, type regedit, and then click OK.
  2. Locate and then click the following registry subkey:
    HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control
  3. In the right pane, locate the ServicesPipeTimeout entry.

    Note If the ServicesPipeTimeout entry does not exist, you must create it. To do this, follow these steps:
     
    1. On the Edit menu, point to New, and then click DWORD Value.
    2. Type ServicesPipeTimeout, and then press ENTER.
  4. Right-click ServicesPipeTimeout, and then click Modify.
  5. Click Decimal, type 60000, and then click OK.

    This value represents the time in milliseconds before a service times out.
  6. Restart the computer.

18 February 2020

Upgradation of SQL Server 2008r2 to 2014 Fails - Valid DSN, Valid Database compatibility level

The below error screen will appear during installation process, the fix is very simple step we need to configure the SSRS database, below screens are self explanatory.

ERROR SCREEN


Open SSRS Configuration Manager and  configure the report server database.

Once its configured we can see below screen.


Re-run the rules and it should go through.

17 February 2020

SQL Server 2014 SP3 Fails - User Data Directory in registry is not valid



Below is the error screen we receive when the SQL Server SP3 Fails, please follow below steps to resolve the issue.


Resolution:

Step1: Go to regedit

Step 2: Crawl to below location
HKLM\SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQLServer

Step3: If there is no DefaultDATA and DefaultLog entries, please add with the path of DATA and Log Files. If exists please verify the location details and correct it.

Step4: Restart the server.

Step5; RUn the setup again.






05 March 2019

General - GDR, SP, CU

What's the difference in a GDR, a Cumulative Update, CTP, RC, and a Service Pack?

CTP:
Microsoft changed the terminology for SQL Server pre-releases.
They are now referred to as CTPs (Community Technology Previews).

RC:
As the product enters it's final stages before release, the feature set is complete and the product is undergoing final testing, it's called an RC (Release Candidate).

GA:
After a product has undergone significant testing and it's determined that no more changes will be made to the product before release, it's sometimes said that the product has gone golden. It's also called a GA (General Availability) release.

RTM:
Once the bits been turned over to a company to mass produce the media (CDs, DVDs, etc), it's RTM'd (Released To Manufacturing).

GDR:
Over time, Hot Fixes are created by the dev team to address specific product issues affecting certain customers. Sometimes the issue is so wide spread, a GDR (General Distribution Release) is issued so that all customers will receive the updates.


CU:
CU (Cumulative Update) is created that contains all of the applicable hot fixes.

SP:
Once a large enough collection of changes have been gathered, an SP (Service Pack) will be issued.

Latest:

An Incremental Servicing Model is available from the SQL Server team to deliver hotfixes for reported problems:

https://support.microsoft.com/en-us/help/935897/an-incremental-servicing-model-is-available-from-the-sql-server-team-t

Going ahead we need to apply only CU to SQL Server to bring the system into servicing support cycle.

More On:  https://blogs.msdn.microsoft.com/sqlreleaseservices/announcing-the-modern-servicing-model-for-sql-server/

https://blogs.msdn.microsoft.com/sqlreleaseservices/announcing-updates-to-the-sql-server-incremental-servicing-model-ism/

01 March 2019

EXECUTE permission was denied on the object 'sp_enable_sql_debug'


The SQL code was failing for one DB User with DBO permissions on the databases it was accessing. 

Problem: There was one stored procedure under database DB1 at some point it used to call other stored procedures from DB2. This caused failure when tried to analyse the issue using DEBUG method.


SOLUTION: Its fixed for us by doing following changes at code and DB level.

Code Level:
11)      Impersonate method
·         With execute as [login]
·         Execute as login=[login name]

22)      Fully qualified database object names

Administration Side:
11)     Grant user granted public role on master to read objects.
22)      Granting View Server State at instance level.


26 October 2018

19 October 2018

Data and Log File Move to New Location (Move Script)

Below is the script we can use to move the data and log files for the databases except master.


DECLARE
    @counter    INT = 1,
    @max        INT = 0,
    @NEW_DATA_PATH VARCHAR(500)='E:\XXXX\Data',
    @NEW_LOG_PATH VARCHAR(500)='F:\XXXX\Log'
  
DECLARE @FILE_LIST TABLE (
    [ID]    int IDENTITY,
    [DBNAME] VARCHAR(100),
    [LNAME]   VARCHAR(100),
    [PNAME]   VARCHAR(500),
    [TYPE_DESC]  VARCHAR(50)
    )  
INSERT INTO @FILE_LIST
SELECT n.NAME,f.NAME,f.PHYSICAL_NAME,f.TYPE_DESC
FROM MASTER.SYS.MASTER_FILES f,MASTER.SYS.DATABASES n WHERE n.NAME not in('MASTER') 
and f.DATABASE_ID=n.DATABASE_ID

SELECT @max = COUNT([ID]) FROM @FILE_LIST

WHILE @counter <= @max
BEGIN

 DECLARE @FILE_TYPE VARCHAR(100),
         @DBNAME VARCHAR(100),
         @LOGICAL_NAME VARCHAR(100),
         @PHYSICAL_NAME VARCHAR(500) ;
          
 SELECT @FILE_TYPE=TYPE_DESC,@DBNAME=[DBNAME],@LOGICAL_NAME=[LNAME],
 @PHYSICAL_NAME=SUBSTRING([PNAME],LEN([PNAME])-CHARINDEX('\',REVERSE([PNAME]))+2,LEN([PNAME])-1) 
 FROM @FILE_LIST WHERE [ID] = @counter
    
    IF(@FILE_TYPE='ROWS')
    BEGIN
    --ALTER DATABASE database_name MODIFY FILE ( NAME = logical_name, FILENAME = 'new_path\os_file_name' );
        --PRINT @FILE_TYPE+','+@DBNAME+','+@LOGICAL_NAME+','+@PHYSICAL_NAME
        PRINT 'USE MASTER 
               GO 
               ALTER DATABASE '+@DBNAME+' MODIFY FILE ( NAME = '+@LOGICAL_NAME+', FILENAME = '''+@NEW_DATA_PATH+'\'+@PHYSICAL_NAME+''')
               GO'
  END
  ELSE
   PRINT 'USE MASTER 
          GO 
          ALTER DATABASE '+@DBNAME+' MODIFY FILE ( NAME = '+@LOGICAL_NAME+', FILENAME = '''+@NEW_LOG_PATH+'\'+@PHYSICAL_NAME+''')
          GO'
     SET @counter = @counter + 1
      
 END

09 June 2018

Delete Maintenance Plans

We need to perform the below steps to delete the jobs or maintenance plans in such cases from sysmaintplan_log table or fromsysmaintplan_subplans table .
Step 1: 
Execute the below query to obtain the Maintenance plan name and Id 
SELECT NAME, ID FROM MSDB..SYSMAINTPLAN_PLANS 
Step 2: 
Replace the Id obtained from Step 1 into the below query and delete the entry from log table
DELETE FROM SYSMAINTPLAN_LOG WHERE PLAN_ID=' ' 
Step 3: 
Replace the Id obtained from Step 1 into the below query and delete the entry from subplans table as shown below,
DELETE FROM SYSMAINTPLAN_SUBPLANS WHERE PLAN_ID = ' '
Step 4: 
Finally delete the maintenance plan using the below query where ID is obtained from Step1
DELETE FROM SYSMAINTPLAN_PLANS WHERE ID = ' '
Step 5: 
Check and delete the jobs from SSMS if it exists.

Many thanks to kapil

10 May 2018

Cannot detach a suspect or recovery pending database. It must be repaired or dropped.

Note: Below method of removing database is only when database shows RECOVERY_PENDING because of  MDF/LDF files missing.

Solution:

ALTER DATABASE DBNAME SET OFFLINE
GO
sp_detach_db 'DBNAME'
GO


In Other Cases Please Refer to (Please Note: Check with customer for dataloss)

https://dbamohsin.wordpress.com/2012/01 /23/cannot-detach-a-suspect-or-recovery-pending-database/

Prefer: Use latest backups available to restore the database.