Hiển thị các bài đăng có nhãn MSSQL. Hiển thị tất cả bài đăng
Hiển thị các bài đăng có nhãn MSSQL. Hiển thị tất cả bài đăng

Thứ Năm, 21 tháng 9, 2023

[MSSQL] Lỗi không start được sau khi update

 Sau khi update SQL mà bị lỗi không start lại được dịch vụ, kiểm tra log SQL có báo lỗi liên quan đến database master 


Script level upgrade for database 'master' failed because upgrade step 'u_tables.sql' encountered error 25641, state 0, severity 16. This is a serious error condition which might interfere with regular operation and the database will be taken offline. If the error happened during upgrade of the 'master' database, it will prevent the entire SQL Server instance from starting. Examine the previous errorlog entries for errors, take the appropriate corrective actions and re-start the database so that the script upgrade steps run to completion.


Để start lại được SQL thì càn thêm biến /T902 để khi start SQL sẽ bỏ qua script update

    net start mssql$instancename /T902

Hoặc khai báo tham số này trong SQL Configuration Manager




Thứ Năm, 9 tháng 9, 2021

[ASP.NET][MSSQL] Web ASP truy vấn SQL chậm qua network

Tình huống khi website asp.net truy cập chậm có liên quan đến truy vấn sql khi server web và server sql thuộc 2 server khác nhau

Quá trình kiểm tra lưu lượng network nếu sử dụng bandwidth nhiều mỗi lần có truy vấn database . Và kiểm tra Resource Waits trên SQL chỉ số Network I/O cao, có nghĩa là ứng dụng (application) không sử dụng hết lưu lượng dữ liệu mà SQL trả về, dẫn tới bị nghẽn cổ chai. mặc dù bandwidth network còn rất rộng và chưa sử dụng hết.

Để cải thiện, có thể kiểm tra cài đặt MARS trong ConnectionString.

MultipleActiveResultSets=True

Nếu có sử dụng thông số này thì bỏ đi hoặc set lại thành False.


Kếu quả Test thực tế trước và sau khi bỏ MultipleActiveResultSets : TTFB trang web giảm 1 nửa, bandwidth network tăng gấp đôi.




Thứ Năm, 4 tháng 3, 2021

[MSSQL] Tìm giá trị chuỗi trong Database SQL Server

Để tìm 1 giá trị dạng text (chuỗi) trong toàn bộ table trong Database SQL Server.


USE DATABASE_NAME

DECLARE @SearchStr nvarchar(100) = 'SEARCH_TEXT'

DECLARE @Results TABLE (ColumnName nvarchar(370), ColumnValue nvarchar(3630))

SET NOCOUNT ON

DECLARE @TableName nvarchar(256), @ColumnName nvarchar(128), @SearchStr2 nvarchar(110)

SET  @TableName = ''

SET @SearchStr2 = QUOTENAME('%' + @SearchStr + '%','''')

WHILE @TableName IS NOT NULL

BEGIN

    SET @ColumnName = ''

    SET @TableName = 

    (

        SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))

        FROM     INFORMATION_SCHEMA.TABLES

        WHERE         TABLE_TYPE = 'BASE TABLE'

            AND    QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName

            AND    OBJECTPROPERTY(

                    OBJECT_ID(

                        QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)

                         ), 'IsMSShipped'

                           ) = 0

    )

    WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)

    BEGIN

        SET @ColumnName =

        (

            SELECT MIN(QUOTENAME(COLUMN_NAME))

            FROM     INFORMATION_SCHEMA.COLUMNS

            WHERE         TABLE_SCHEMA    = PARSENAME(@TableName, 2)

                AND    TABLE_NAME    = PARSENAME(@TableName, 1)

                AND    DATA_TYPE IN ('char', 'varchar', 'nchar', 'nvarchar', 'int', 'decimal')

                AND    QUOTENAME(COLUMN_NAME) > @ColumnName

        )

        IF @ColumnName IS NOT NULL

        BEGIN

            INSERT INTO @Results

            EXEC

            (

                'SELECT ''' + @TableName + '.' + @ColumnName + ''', LEFT(' + @ColumnName + ', 3630) 

                FROM ' + @TableName + ' (NOLOCK) ' +

                ' WHERE ' + @ColumnName + ' LIKE ' + @SearchStr2

            )

        END

    END    

END

SELECT ColumnName, ColumnValue FROM @Results


Ngoài ra, có thể sử dụng ApexSQL Search miễn phí trên SSMS : https://www.apexsql.com/sql-tools-search.aspx


Thứ Sáu, 8 tháng 5, 2020

[MSSQL] Kiểm tra mức sử dụng Memory của Database và Object

Kiểm tra mức sử dụng RAM của Database

-- Note: querying sys.dm_os_buffer_descriptors
-- requires the VIEW_SERVER_STATE permission.

DECLARE @total_buffer INT;

SELECT @total_buffer = cntr_value
FROM sys.dm_os_performance_counters 
WHERE RTRIM([object_name]) LIKE '%Buffer Manager'
AND counter_name = 'Database Pages';

;WITH src AS
(
SELECT 
database_id, db_buffer_pages = COUNT_BIG(*)
FROM sys.dm_os_buffer_descriptors
--WHERE database_id BETWEEN 5 AND 32766
GROUP BY database_id
)
SELECT
[db_name] = CASE [database_id] WHEN 32767 
THEN 'Resource DB' 
ELSE DB_NAME([database_id]) END,
db_buffer_pages,
db_buffer_MB = db_buffer_pages / 128,
db_buffer_percent = CONVERT(DECIMAL(6,3), 
db_buffer_pages * 100.0 / @total_buffer)
FROM src
ORDER BY db_buffer_MB DESC; 


Kiểm tra mức sử dụng RAM của Object trong Database

USE [database_name]
GO

;WITH src AS
(
SELECT
[Object] = o.name,
[Type] = o.type_desc,
[Index] = COALESCE(i.name, ''),
[Index_Type] = i.type_desc,
p.[object_id],
p.index_id,
au.allocation_unit_id
FROM
sys.partitions AS p
INNER JOIN
sys.allocation_units AS au
ON p.hobt_id = au.container_id
INNER JOIN
sys.objects AS o
ON p.[object_id] = o.[object_id]
INNER JOIN
sys.indexes AS i
ON o.[object_id] = i.[object_id]
AND p.index_id = i.index_id
WHERE
au.[type] IN (1,2,3)
AND o.is_ms_shipped = 0
)
SELECT
src.[Object],
src.[Type],
src.[Index],
src.Index_Type,
buffer_pages = COUNT_BIG(b.page_id),
buffer_mb = COUNT_BIG(b.page_id) / 128
FROM
src
INNER JOIN
sys.dm_os_buffer_descriptors AS b
ON src.allocation_unit_id = b.allocation_unit_id
WHERE
b.database_id = DB_ID()
GROUP BY
src.[Object],
src.[Type],
src.[Index],
src.Index_Type
ORDER BY
buffer_pages DESC;

Thứ Bảy, 20 tháng 4, 2019

[ASP.NET] SQL : The wait operation timed out

Do query thực thi quá lâu, mặc định timeout là 30s. Trường hợp này có thể set tăng timeout trong code thực thi query.

In your code where you run the stored procedure you should have something like this:

SqlCommand c = new SqlCommand(...)
//...
Add such a line of code:

c.CommandTimeout = 0;
This will wait as much time as needed for the operation to complete.

đây là 1 ví dụ về set timoute exute query
Trên vd đang set 0 là không limit , Bạn có thể set 60 hoặc 120 chẳng hạn

[ASP.NET] Lỗi liên quan SQL CLR , khi move DB qua server mới web không chạy

An error occurred in the Microsoft .NET Framework while trying to load assembly id 65536. The server may be running out of resources, or the assembly may not be trusted. Run the query again, or check documentation to see how to solve the assembly trust issues. For more information about this error:
System.IO.FileLoadException: Could not load file or assembly 'groupconcat, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. An error relating to security occurred. (Exception from HRESULT: 0x8013150A

loging in with sa, restoring DB again and setting TRUSTWORTHY ON

USE [apel_vn_db];
EXEC sp_configure 'clr enabled' ,1
GO

USE [apel_vn_db];
GO

EXEC sp_changedbowner 'sa'
USE [apel_vn_db];
GO

ALTER DATABASE [apel_vn_db] SET TRUSTWORTHY ON;

Thứ Tư, 29 tháng 8, 2018

[MSSQL] Kill Connnection to Database

=======Kill All Active Connections To A Database===
ALTER DATABASE YourDatabase SET SINGLE_USER WITH ROLLBACK IMMEDIATE
   
--do you stuff here
   
ALTER DATABASE YourDatabase SET MULTI_USER


------------------or-------------------------
/*For MS SQL Server 2012 and above*/

USE [master];

DECLARE @kill varchar(8000) = '';  
SELECT @kill = @kill + 'kill ' + CONVERT(varchar(5), session_id) + ';'  
FROM sys.dm_exec_sessions
WHERE database_id  = db_id('MyDB')

EXEC(@kill);

/*For MS SQL Server 2000, 2005, 2008*/

USE master;

DECLARE @kill varchar(8000); SET @kill = '';  
SELECT @kill = @kill + 'kill ' + CONVERT(varchar(5), spid) + ';'  
FROM master..sysprocesses  
WHERE dbid = db_id('MyDB')

EXEC(@kill); 

------------------------------------------------
/* For a specific database */

SELECT 'KILL ' + CAST(session_id AS VARCHAR(10))
FROM sys.dm_exec_sessions
WHERE is_user_process = 1
       AND database_id = DB_ID('database name');

/* For all databases */

SELECT 'KILL ' + CAST(session_id AS VARCHAR(10))
FROM sys.dm_exec_sessions
WHERE is_user_process = 1;

=> Copy kêt quả lệnh Select và  Run

Thứ Năm, 4 tháng 5, 2017

[MSSQL] Find out CPU usages of all different SQL Server Objects

In SQL Server Management Studio run the "Performance - Top Queries By Total CPU Time" report.


In this post, I provide you one script to find out CPU usages of all different SQL Server Objects.
This script is very important for DBA when DBA monitoring CPU usages.
Below is a script:

http://www.dbrnd.com/2015/06/sql-server-cpu-usage-per-different-objects/







Measure CPU Usage Per Database :

 WITH cte as ( SELECT SDEPA.DatabaseID , SUM (SDEQS.total_worker_time) AS CPUTimeInMiliSeconds FROM sys.dm_exec_query_stats SDEQS CROSS APPLY (SELECT CAST(value as int) AS [DatabaseID] FROM sys.dm_exec_plan_attributes(SDEQS.plan_handle) WHERE attribute = N'dbid') SDEPA GROUP BY SDEPA.DatabaseID) SELECT COALESCE(DB_NAME(DatabaseID), '{Overhead Processes}') as [Database] , CAST ([CPUTimeInMiliSeconds] * 1.0 / SUM ([CPUTimeInMiliSeconds]) OVER () * 100.0 as DECIMAL(6, 3)) AS [CPUTime%] FROM cte ORDER BY CAST ([CPUTimeInMiliSeconds] * 1.0 / SUM ([CPUTimeInMiliSeconds]) OVER () * 100.0 as DECIMAL(6, 3)) DESC;


Thống kê top query trên database cụ thể:

SELECT TOP 10 SUBSTRING(qt.TEXT, (qs.statement_start_offset/2)+1,
((CASE qs.statement_end_offset
WHEN -1 THEN DATALENGTH(qt.TEXT)
ELSE qs.statement_end_offset
END - qs.statement_start_offset)/2)+1),
qs.execution_count,
qs.total_logical_reads, qs.last_logical_reads,
qs.total_logical_writes, qs.last_logical_writes,
qs.total_worker_time,
qs.last_worker_time,
qs.total_elapsed_time/1000000 total_elapsed_time_in_S,
qs.last_elapsed_time/1000000 last_elapsed_time_in_S,
qs.last_execution_time,
qp.query_plan,
[DB] = DB_NAME(qt.[dbid])
FROM sys.dm_exec_query_stats qs
CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) qt
CROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) qp
--ORDER BY qs.total_logical_reads DESC -- logical reads
--ORDER BY qs.total_logical_writes DESC -- logical writes
where DB_NAME(qt.[dbid]) = 'db_name'
ORDER BY qs.total_worker_time DESC -- CPU time

Thứ Năm, 1 tháng 12, 2016

[MSSQL] List Database (expand databse) in SSMS Slow

https://social.msdn.microsoft.com/Forums/sqlserver/en-US/99bbcb47-d4b5-4ec0-9e91-b1a23a655844/ssms-2012-extremely-slow-expanding-databases?forum=sqltools

lý do có nhiều database đang set auto_close = on 
=> xử lý là set thuộc tính database  auto_close = off

SELECT 'Alter Database [' +name+'] set AUTO_CLOSE OFF'
FROM master.sys.databases AS dtb 
WHERE is_auto_close_on = 1
ORDER BY name

=> copy lệnh run trên query mới

Used this script to find those databases: 
SELECT name, is_auto_close_on, is_auto_shrink_on FROM master.sys.databases AS dtb 
WHERE is_auto_close_on = 1 OR is_auto_shrink_on = 1
ORDER BY name

giải thích thuộc tính  auto_close

 According to Books Online:
When set to ON, the database is shut down cleanly and its resources are freed after the last user exits. The database automatically reopens when a user tries to use the database again.

    When set to OFF, the database remains open after the last user exits

Thứ Tư, 9 tháng 4, 2014

[MSSQL] Full Text Search/Full Text Index

Check full text search install

SELECT FULLTEXTSERVICEPROPERTY('IsFullTextInstalled')
IF IT RETURNS 1, fulltextsearch functionality is installed in your server.

SELECT DATABASEPROPERTY('databasename','isfulltextenabled')

output : 1 then is enabled             0 then not


Enable a Database for Full-Text Indexing (SQL Server Management Studio)
http://technet.microsoft.com/en-us/library/ms403375%28v=sql.90%29.aspx

In Microsoft SQL Server 2005, by default, all user-created databases are full-text enabled. However, there may be situations in which full-text indexing has been disabled.
  1. In Object Explorer, expand the server group, right-click the database for which you want to enable full-text indexing, and then select Properties.
  2. Select the Files page, and then select Use full-text indexing.
     
In SQL Server 2008, all user-created databases are always full-text enabled and cannot be disabled.  

Thứ Năm, 3 tháng 4, 2014

[MSSQL] Shrink Database MSSQL

http://msdn.microsoft.com/en-us/library/ms189493%28v=sql.90%29.aspx 

Example:
A. Shrinking a data file to a specified target size
The following example shrinks the size of a data file named DataFile1 in the UserDB user database to 7 MB.

USE UserDB;
GO
DBCC SHRINKFILE (DataFile1, 7);
GO

B. Shrinking a log file to a specified target size
The following example shrinks the log file in the AdventureWorks database to 1 MB. To allow the DBCC SHRINKFILE command to shrink the file, the file is first truncated by setting the database recovery model to SIMPLE.

USE AdventureWorks;
GO
-- Truncate the log by changing the database recovery model to SIMPLE.
ALTER DATABASE AdventureWorks
SET RECOVERY SIMPLE;
GO
-- Shrink the truncated log file to 1 MB.
DBCC SHRINKFILE (AdventureWorks_Log, 1);
GO
-- Reset the database recovery model.
ALTER DATABASE AdventureWorks
SET RECOVERY FULL;
GO

C. Truncating a data file
The following example truncates the primary data file in the AdventureWorks database. The sys.database_files catalog view is queried to obtain the file_id of the data file.

USE AdventureWorks;
GO
SELECT file_id, name
FROM sys.database_files;
GO
DBCC SHRINKFILE (1, TRUNCATEONLY);

D. Emptying a file
The following example demonstrates the procedure for emptying a file so that it can be removed from the database. For the purposes of this example, a data file is first created and it is assumed that the file contains data.

USE AdventureWorks;
GO
-- Create a data file and assume it contains data.
ALTER DATABASE AdventureWorks 
ADD FILE (
    NAME = Test1data,
    FILENAME = 'C:\t1data.ndf',
    SIZE = 5MB
    );
GO
-- Empty the data file.
DBCC SHRINKFILE (Test1data, EMPTYFILE);
GO
-- Remove the data file from the database.
ALTER DATABASE AdventureWorks
REMOVE FILE Test1data;

[MSSQL] Enable Broker in MSSQL

Enabling Service Broker
The following T-Sql enables or disabled service broker on SqlServer 2005. The Service Broker is required by .net for SqlCacheDependency support

-- Enable Service Broker:
ALTER DATABASE [Database Name] SET ENABLE_BROKER;

-- Disable Service Broker:
ALTER DATABASE [Database Name] SET DISABLE_BROKER;

Is Service Broker enabled?
To determine whether or not Service Broker is enabled for a particular database, execute the following T-SQL
SELECT is_broker_enabled FROM sys.databases WHERE name = 'Database name';

is_broker_enabled will be 1 if Service Broker is enabled for the given database, otherwise it'll be 0.

[MSSSQL] Xem số connection vào DB MSSQL

-- Get a count of SQL connections by login_name
select loginame, count(loginame)as Connections from master.dbo.sysprocesses
group by loginame
ORDER BY Connections desc

-----SQL 2012 tro len
SELECT DB_NAME(database_id) as DBName,
login_name,
COUNT(session_id) as NumberOfConnections
FROM sys.dm_exec_sessions
GROUP BY database_id, login_name
order by NumberOfConnections desc;


-- Get a count of SQL connections by IP address
SELECT ec.client_net_address, es.[program_name],
es.[host_name], es.login_name,
COUNT(ec.session_id) AS [connection count]
FROM sys.dm_exec_sessions AS es
INNER JOIN sys.dm_exec_connections AS ec
ON es.session_id = ec.session_id 
GROUP BY ec.client_net_address, es.[program_name], es.[host_name], es.login_name
ORDER BY [connection count] desc;

[MSSQL] Modify default schema DB MSSQL

exec sp_MSforeachtable "ALTER SCHEMA dbo TRANSFER ? PRINT '? modified' "
=>change schema all table

EXEC('sp_changeobjectowner @objname = ''username.tablename'', @newowner = dbo')

Hoặc có thể chạy lệnh để thay đổi schema từ tên user.table --> dbo.table

USE ngochienco;
    GO
    ALTER SCHEMA dbo TRANSFER ngochien3101.orderlist;
    GO

Change all object in database (table, procedure, view)

Part 1
    Open Microsoft SQL Server Management Studio and log in.
    Click the New Query button.
    Paste the following script into the New Query box changing oldschema to the name of the current schema:

    SELECT 'ALTER SCHEMA dbo TRANSFER ' + s.Name + '.' + o.Name
    FROM sys.Objects o
    INNER JOIN sys.Schemas s on o.schema_id = s.schema_id
    WHERE s.Name = 'oldschema'
    And (o.Type = 'U' Or o.Type = 'P' Or o.Type = 'V')

    Click Execute

This query will result in output in the Results box which looks similar to the output below:

    ALTER SCHEMA dbo TRANSFER yourschema.Table1
    ALTER SCHEMA dbo TRANSFER yourschema.Table2
    ALTER SCHEMA dbo TRANSFER yourschema.Table3
 

Part 2

    Click the New Query button.
    Paste the queries from the output of Part 1 into your new Query box
    Click Execute

This will transfer the schema name across to the new schema, also changing the stored procedures and views.

Cách 2:

/*
    Change ALL database object ownership to dbo, including;
    
        U = user table
        V = view
        s = system table
        p = stored proc
        FN = function
    
    Variables:
    
        %%DATABASENAME%%        - Database Name you're updating
        %%CURRENTOBJECTOWNERNAME%%    - CURRENT object owner name
*/

declare @object varchar(517)
declare @dbname nvarchar( 128 )

/* BE SURE TO DECLARE THE CORRECT DATABASE HERE!!!! */

SELECT @dbname = '%%DATABASENAME%%'

declare objects cursor for select name
    from sysobjects o
    where o.type in ('U','V','S','P','FN') and
    convert(sysname,user_name(o.uid)) = '%%CURRENTOBJECTOWNERNAME%%' /* this is the database-USER you are changing FROM */

open objects
    while(1=1)
    begin
    
        fetch next from objects into @object
        if @@fetch_status < 0 break
            exec ('sp_changeobjectowner ' + '''' + '%%CURRENTOBJECTOWNERNAME%%' + '.' +  @object + '''' + ', ' + '''' + 'dbo' + '''' )
    end
    
deallocate objects

[MSSQL] FIX DATABASE SUSPECT

use master
EXEC sp_resetstatus dbname
ALTER DATABASE dbname SET EMERGENCY 
DBCC checkdb(dbname) 
ALTER DATABASE dbname SET SINGLE_USER WITH ROLLBACK IMMEDIATE 
DBCC CheckDB (dbname, REPAIR_ALLOW_DATA_LOSS) 
ALTER DATABASE dbname SET MULTI_USER