Labels

admin (1) aix (1) alert (1) always-on (2) Architecture (1) aws (3) Azure (1) backup (3) BI-DWH (10) Binary (3) Boolean (1) C# (1) cache (1) casting (3) cdc (1) certificate (1) checks (1) cloud (3) cluster (1) cmd (7) collation (1) columns (1) compilation (1) configurations (7) Connection-String (2) connections (6) constraint (6) copypaste (2) cpu (2) csv (3) CTE (1) data-types (1) datetime (23) db (547) DB2 (1) deadlock (2) Denali (7) device (6) dotNet (5) dynamicSQL (11) email (5) encoding (1) encryption (4) errors (124) excel (1) ExecutionPlan (10) extended events (1) files (7) FIPS (1) foreign key (1) fragmentation (1) functions (1) GCP (2) gMSA (2) google (2) HADR (1) hashing (3) in-memory (1) index (3) indexedViews (2) insert (3) install (10) IO (1) isql (6) javascript (1) jobs (11) join (2) LDAP (2) LinkedServers (8) Linux (15) log (6) login (1) maintenance (3) mariadb (1) memory (4) merge (3) monitoring (4) MSA (2) mssql (444) mssql2005 (5) mssql2008R2 (20) mssql2012 (2) mysql (36) MySQL Shell (5) network (1) NoSQL (1) null (2) numeric (9) object-oriented (1) offline (1) openssl (1) Operating System (4) oracle (7) ORDBMS (1) ordering (2) Outer Apply (1) Outlook (1) page (1) parameters (2) partition (1) password (1) Performance (103) permissions (10) pivot (3) PLE (1) port (4) PostgreSQL (14) profiler (1) RDS (3) read (1) Replication (12) restore (4) root (1) RPO (1) RTO (1) SAP ASE (48) SAP RS (20) SCC (4) scema (1) script (8) security (10) segment (1) server (1) service broker (2) services (4) settings (75) SQL (74) SSAS (1) SSIS (19) SSL (8) SSMS (4) SSRS (6) storage (1) String (35) sybase (57) telnet (2) tempdb (1) Theory (2) tips (120) tools (3) training (1) transaction (6) trigger (2) Tuple (2) TVP (1) unix (8) users (3) vb.net (4) versioning (1) windows (14) xml (10) XSD (1) zip (1)
Showing posts with label mssql2008R2. Show all posts
Showing posts with label mssql2008R2. Show all posts

Cannot schema bind view because name 'TableName' is invalid for schema binding. Names must be in two-part format and an object cannot reference itself.

Error message:
Cannot schema bind view 'dbo.ViewName' because name 'TableName' is invalid for schema binding. Names must be in two-part format and an object cannot reference itself.

Cause and solution:
Call tables with the schema name: dbo.TableName (not only TableName).

It's can happen in indexed views query.

Reporting Execution Log

SELECT * 
FROM [ReportServer].[dbo].[ExecutionLog2] 
ORDER BY TimeStart desc

GROUPING SETS

A GROUP BY clause that uses GROUPING SETS can generate a result set equvalent to that generated by a UNION ALL of multiple simple GROUP BY clauses.

SELECT TestName, year, SUM(TestSales)FROM TestTable
GROUP BY GROUPING SETS ((TestName), (TestYear))

The results will be the same as:

SELECT NULL as TestName, TestYear, SUM(TestSales)FROM TestTable GROUP BY TestYear
UNION ALL
SELECT TestName, NULL as TestYear, SUM(TestSales)FROM TestTable GROUP BY TestName


Plan guide for associating query

sp_create_plan_guide creates a plan guide for associating query hints or actual query plans with queries in a database.

EXEC sp_create_plan_guide 
    @name =  N'Guide1',
    @stmt = N'SELECT *
              FROM Sales.SalesOrderHeader AS h 
              INNER JOIN Sales.Customer AS c 
                 ON h.CustomerID = c.CustomerID
              INNER JOIN Sales.SalesTerritory AS t 
                 ON c.TerritoryID = t.TerritoryID
              WHERE t.CountryRegionCode = @Country_region',
    @type = N'OBJECT',
    @module_or_batch = N'Sales.GetSalesOrderByCountry',
    @params = NULL,
    @hints = N'OPTION (OPTIMIZE FOR (@Country_region = N''US''))';


EXEC sp_create_plan_guide 
    @name = N'Guide1', 
    @stmt = N'SELECT TOP 1 * 
              FROM Sales.SalesOrderHeader 
              ORDER BY OrderDate DESC', 
    @type = N'SQL',
    @module_or_batch = NULL, 
    @params = NULL, 
    @hints = N'OPTION (MAXDOP 1)';




sp_control_plan_guide drops, enables, or disables a plan guide.

EXEC sp_control_plan_guide N'DROP', N'Guide1'

Get the time zone offset in MSSQL

SELECT SYSDATETIMEOFFSET()
-- return datetime + time zone offset.

sys.dm_os_sys_memory

SELECT * FROM sys.dm_os_sys_memory

Returns a complete picture of memory at the operating system level, including information about total and available physical memory, total and available page memory, system cache, kernel space and so forth.

Auditing in SQL Server 2008

Auditing an instance of SQL Server or a SQL Server database involves tracking and logging events that occur on the system.

Auditing declaration and executions steps:
  1. Create a SQL Server Audit object.
  2. Create an Audit Specification (can be at the server or database level).
  3. Turn it on.

-- Create a SQL Server Audit object
CREATE SERVER AUDIT [ItaiAudit]
TO FILE 
( FILEPATH = N'D:\FolderA\'
,MAXSIZE = 100 MB
,MAX_ROLLOVER_FILES = 2147483647
,RESERVE_DISK_SPACE = OFF
)
WITH
( QUEUE_DELAY = 1000
,ON_FAILURE = CONTINUE
)
GO

-- Create an Audit Specification (database level)
CREATE DATABASE AUDIT SPECIFICATION [ItaiAuditSpecification]
FOR SERVER AUDIT [ItaiAudit]
ADD (UPDATE ON OBJECT::[dbo].[StamTable] BY [dbo]),
ADD (SELECT ON OBJECT::[dbo].[StamTable2] BY [dbo])
WITH (STATE = OFF)
GO


-- Another example: Create an Audit Specification to get logins (server level)
CREATE SERVER AUDIT SPECIFICATION [AuditSpec_itai_RG]
FOR SERVER AUDIT [Audit_itai_RG]
ADD (FAILED_LOGIN_GROUP),
ADD (SUCCESSFUL_LOGIN_GROUP)
WITH (STATE = ON)
GO



-- Turn it on
ALTER SERVER AUDIT ItaiAudit WITH (STATE = ON)
GO

-- Get auditing data from the file:
SELECT * 
FROM fn_get_audit_file('D:\FolderA\Audit*.sqlaudit',default, default) a

Note: Auditing is a SQL 2008 Enterprise version only feature.

msdn: Auditing in SQL Server 2008
msdn: Understanding SQL Server Audit

sys.dm_os_windows_info

Returns one row that displays Windows operating system version information.

SELECT * FROM sys.dm_os_windows_info


Note: Available from MSSQL 2008 R2 SP1.

sys.dm_server_services

Returns information about the SQL Server and SQL Server Agent services in the current instance of SQL Server.

SELECT * FROM sys.dm_server_services


Note: Available from MSSQL 2008 R2 SP1.

sys.dm_server_registry

Returns configuration and installation information that is stored in the Windows registry for the current instance of SQL Server

SELECT * FROM sys.dm_server_registry


Note: Available from MSSQL 2008 R2 SP1.

sys.dm_os_volume_stats

Returns information about the operating system volume

SELECT * FROM sys.dm_os_volumne_stats (database_id, file_id)

-- get data for all of the DBs:
SELECT ... 
FROM sys.master_files f 
CROSS APPLY sys.dm_os_volume_stats(f.database_id, f.file_id) vs


Note: Available from MSSQL 2008 R2 SP1.

FORCESEEK and FORCESCAN

FORCESEEK
FORCESEEK [ (index_value(index_column_name [ ,... n ] )) ]

Use the FORCESEEK hint to Specify the query optimizer use only an index seek operation.

SELECT ..... FROM Sales.SalesOrderHeader h
INNER JOIN Sales.SalesOrderDetail AS d WITH (FORCESEEK)
ON h.SalesOrderID = d.SalesOrderID .......

SELECT ..... FROM Sales.SalesOrderHeader h
INNER JOIN Sales.SalesOrderDetail AS d WITH (FORCESEEK (INDEX_NAME ((COLUMN_NAME))) 
ON h.SalesOrderID = d.SalesOrderID .......


FORCESCAN

Use the FORCESCAN hint to force the query optimizer to perform a scan operation

SELECT ..... FROM Sales.SalesOrderHeader h
INNER JOIN Sales.SalesOrderDetail AS d WITH (FORCESCAN) 
ON h.SalesOrderID = d.SalesOrderID .......



SQL Server 2008 IntelliSense Does Not Work

When IntelliSense is not work, it's probably because of one of those reasons:
  • You are connected to SQL Server 2008 Edition and above - even if you work with SSMS 2008 - there is no IntelliSense to MSSQL Editions under 2008.
  • Check that Intellisense is enabled, look at Query-->Intellisense Enabled, or at Tools-->Options-->Text Editor-->Transact-SQL-->Intellisense, and check there that the 'Enable Intellisense' checkbox is checked.
  • Maybe IntelliSense should be refreshed with the latest changes. When restart the SSMS,  IntelliSense is refreshed. In order to refresh it while working, go to Edit-->IntelliSense-->Refresh Local Cache.
  • If one or more databases is Offline - IntelliSense is not work for all of the databases in the server.

Performance Dashboard Reports in SQL Server 2008

While running the Performance Dashboard scripts, we will get the following error:
Msg 207, Level 16, State 1, Procedure usp_Main_GetCPUHistory, Line 6
Invalid column name 'cpu_ticks_in_ms'.
Msg 15151, Level 16, State 1, Line 1
Cannot find the object 'usp_Main_GetCPUHistory', because it does not exist or you do not have permission.

To fix it, we need to edit MS_PerfDashboard.usp_Main_GetCPUHistory:

create procedure MS_PerfDashboard.usp_Main_GetCPUHistory
as
begin
declare @ts_now bigint
--select @ts_now = cpu_ticks / convert(float, cpu_ticks_in_ms) from sys.dm_os_sys_info
select @ts_now = cpu_ticks / convert(float, ms_ticks) from sys.dm_os_sys_info
..................

Passing a datatable to a Stored Procedure in SQL Server 2008

Table-valued parameters are a new parameter type in SQL Server 2008. 
Table-valued parameters are declared by using user-defined table types.

You can use table-valued parameters to send multiple rows of data to a Transact-SQL statement or a routine, such as a stored procedure or function, without creating a temporary table or many parameters.
Of course you can use table-valued parameters in the SQL code.

----------------------------------------
-- create table type
----------------------------------------
CREATE TYPE dbo.TableVariableTest AS TABLE
(
ID int
)
GO
--Note: You can declare a table-valued parameter also with PKs etc.

----------------------------------------
-- create SP that uses the table type
----------------------------------------
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE dbo.SelectTableVariableTestItai
(
    @TableVar dbo.TableVariableTest READONLY
)
AS
BEGIN
    SET NOCOUNT ON;
    
SELECT * 
FROM dbo.Calendar c
JOIN @TableVar v ON v.ID = c.CalID
END
GO

----------------------------------------
-- test:
----------------------------------------
DECLARE @MyTable TableVariableTest

INSERT INTO @MyTable(ID)
VALUES (392),
(477),
(506)

EXEC SelectTableVariableTestItai @TableVar = @MyTable
go


----------------------------------------
-- in the trace it's look like:
----------------------------------------
declare @p1 dbo.TableVariableTest
insert into @p1 values(392)
insert into @p1 values(477)

exec SelectTableVariableTestItai @TableVar=@p1

----------------------------------------
-- the .net code:
----------------------------------------
public DataTable SelectTableVariableTestItai()
{
    DataTable dt = new DataTable();
    dt.Columns.Add("ID", typeof(int));
    DataRow row1 = dt.NewRow();
    DataRow row2 = dt.NewRow();
    row1["ID"] = 392;
    row2["ID"] = 477;
    dt.Rows.Add(row1);
    dt.Rows.Add(row2);

    db.CreateCommand("SelectTableVariableTestItai");
    db.AddParameter("TableVar", dt, SqlDbType.Structured);

    return db.ExecuteDataTable();
}

Unique columns to not NULL values

New in SQL SERVER 2008:
We can define an unique column, that NULL is not need to be unique, or in other words: the unique check is only for not NULL values.

CREATE UNIQUE NONCLUSTERED INDEX IX_TableName_UniqueColumn
ON dbo.TableName (UniqueColumn)
WHERE UniqueColumn IS NOT NULL
GO
 SELECT ID, UniqueColumn FROM TableName WHERE ID in (5, 6, 7)
-- for the example. lets say that the results are: 5, NULL ; 6, NULL ; 7, NULL.
UPDATE TableName SET UniqueColumn = 'test' WHERE ID = 5 --will be success
UPDATE TableName SET UniqueColumn = 'test' WHERE ID = 6 --will be failed
UPDATE TableName SET UniqueColumn = NULL WHERE ID = 5 --will be success

ORIGINAL_DB_NAME()

select ORIGINAL_DB_NAME ()

Returns the database name that is specified by the user.

Resource Governor

Resource Governor enables to manage SQL Server workload and resources by specifying limits on resource consumption by incoming requests.
Available from SQL Server 2008.

Resource Governor creation steps and components:

RESOURCE POOL
CREATE RESOURCE POOL pool_name
[ WITH
    ( [ MIN_CPU_PERCENT =value ]
    [ [ , ] MAX_CPU_PERCENT =value ]
    [ [ , ] MIN_MEMORY_PERCENT =value ]
    [ [ , ] MAX_MEMORY_PERCENT =value ] )
]


WORKLOAD GROUP
CREATE WORKLOAD GROUP group_name
[ WITH
    ( [ IMPORTANCE = { LOW | MEDIUM | HIGH } ]
      [ [ , ] REQUEST_MAX_MEMORY_GRANT_PERCENT =value ]
      [ [ , ] REQUEST_MAX_CPU_TIME_SEC =value ]
      [ [ , ] REQUEST_MEMORY_GRANT_TIMEOUT_SEC =value ]
      [ [ , ] MAX_DOP =value ]
      [ [ , ] GROUP_MAX_REQUESTS =value ] )
 ]
[ USING { pool_name | "default" } ]


CLASSIFIER FUNCTION 
CREATE FUNCTION rgclassifier_v1() RETURNS SYSNAME
WITH SCHEMABINDING
AS
BEGIN
DECLARE @grp_name AS SYSNAME
......
RETURN @grp_name
END

Note: function must be in master DB!

Assign CLASSIFIER FUNCTION to RESOURCE GOVERNOR
ALTER RESOURCE GOVERNOR WITH (CLASSIFIER_FUNCTION= dbo.rgclassifier_v1)

Resources configuration to the WORKLOAD GROUP
ALTER WORKLOAD GROUP groupAdhoc
WITH (REQUEST_MAX_CPU_TIME_SEC = 30)
or
WITH (MAX_CPU_PERCENT = 50)

Activation
ALTER RESOURCE GOVERNOR RECONFIGURE


DMVs and catalog views to monitor RESOURCE GOVERNOR
SELECT * FROM sys.dm_resource_governor_workload_groups
SELECT * FROM sys.dm_resource_governor_resource_pools
SELECT * FROM sys.dm_resource_governor_configuration

SELECT * FROM sys.resource_governor_workload_groups
SELECT * FROM sys.resource_governor_resource_pools
SELECT * FROM sys.resource_governor_configuration


Note:
Resource Governor is available only on the Enterprise, Developer, and Evaluation editions of SQL Server.

Useful links:
Managing SQL Server Workloads with Resource Governor
Resource Governor Concepts
Good videos:
Good and short sumery:
Video, monitor and work from management studio:
Another articles:

Mssql 2008 R2 Restore error: File '.ndf' is claimed by (4) and (3). The WITH MOVE clause can be used to relocate one or more files

Mssql 2008 R2 Restore Error: 
File '.ndf' is claimed by (4) and (3). The WITH MOVE clause can be used to relocate one or more files.

Solutions:
1.
Restore behavior for new DB was changed in SQL 2008:
In 2005, we can create new (empty) DB and restore from bak file to the new DB.
In 2008, Restore from bak file to new DB (that was not created yet).
(Right click on Databases-->Restore Database...)






















Another possible causes of the problem can be (not only for MSSQL 2008):
2.
 Different number of files between the new DB and the source DB.

3.
Attempting to use a file for more than one purpose.

DB upgrade to 2008R2 checklist

Before upgrade:
- Backup database

- Run Upgrade Advisor
Run upgrade advisor for all databases (including system databases) and fix any issue/blocker for upgrade.

Error fix: SQL Server 2008 Upgrade Advisor fails to connect to an instance:
I Skipped this error by enter "default" to the named instance.

After upgrade:
- Update statistics (to ensure performance)
sp_updatestats

- Check Collation

- Check compatibility level
Set compatibility level to 100, by the DB Properties window or by command.
EXEC sp_dbcmptlevel DBNAME, 100

- Updating page or row counts or both for all objects in the current database
DBCC updateusage 0 -- 0 = current DB

- Recreate full text indexes removed from the databases.
- Re-build Full-Text catalogs
ALTER FULLTEXT CATALOG [CATALOGNAME] REBUILD

- Test the application with the new database server 2008.

- It's recommended to check definitions of Users, Schemas, Rules in the new server.


More links: