블로그 이미지
010-9967-0955 보미아빠

카테고리

보미아빠, 석이 (500)
밥벌이 (16)
싸이클 (1)
일상 (1)
Total
Today
Yesterday

달력

« » 2024.5
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31

공지사항

최근에 올라온 글

'보미아빠, 석이'에 해당되는 글 500건

  1. 2016.04.12 adam sp_whoisactive plus tempdb.....usages
  2. 2016.04.12 nul 백업
  3. 2016.04.08 jTDS vs MS JDBC
  4. 2016.04.06 Not every extended event is suited for all situations
  5. 2016.04.05 ssma mysql
  6. 2016.03.28 mstsc shadow:2
  7. 2016.03.25 메모리 관련
  8. 2016.03.22 tcp-ip
  9. 2016.03.22 ag readonly
  10. 2016.03.16 메시지 3456, 수준 16, 상태 1, 줄 1


sp_whoisactive2.txt


Posted by 보미아빠
, |

nul 백업

카테고리 없음 / 2016. 4. 12. 10:36

디스크 읽기 최대성능을 볼 때 쓸만함 

 

 

BACKUP DATABASE tt

TO DISK = 'NUL:'
,DISK   = 'NUL:'
,DISK   = 'NUL:'
,DISK   = 'NUL:'
,DISK   = 'NUL:'
,DISK   = 'NUL:'
,DISK   = 'NUL:'
,DISK   = 'NUL:'
 WITH NO_COMPRESSION
,BUFFERCOUNT = 2200

 

 

backup log tt to
disk ='NUL'
, disk = 'NUL'

 

 

 

Posted by 보미아빠
, |

jTDS vs MS JDBC

카테고리 없음 / 2016. 4. 8. 11:14


1) call pattern 


jTDS 로 PreparedStatement 를 호출하면 sp_prepare sp_execute 를 호출한다. 

MS JDBC 는 sp_prepexec 로 위 두 단계를 하나로 줄여서 실행한다. 한마디로 서버 클라이언트간 round-trip 횟수를 줄여 성능을 높일 수 있다. connectionString 에 prepareSQL=2 라고 옵션을 주면 sp_executesql 로 동작해 한번에 돌릴 수 있고 parameter snipping 도 가능하다. 그런데, 이건 좀 다른 동작 방식이다. 항상 sql 이 날아가야 한다.  



2) parameter snipping


jTDS 로 PreparedStatement 를 사용하면 파라메터 스니핑을 사용하지 못하고 

JDBC 를 사용하면 파라메터 스니핑이 가능하다.....


그런데 감당하지 못하겠으면 SQL Server 레벨에서 disable 가능하다 


Parameter sniffing can be disabled using the documented and supported trace flag 4136. This trace flag is also supported for per-query use via the QUERYTRACEON hint. Both apply from SQL Server 2005 Service Pack 4 onward (and slightly earlier if you are willing to apply cumulative updates to Service Pack 3).



sql server 에서 파라메터 스니핑을 하는 경우(MS JDCB)



             <ParameterList>

              <ColumnReference Column="@P0" ParameterCompiledValue="(1)" ParameterRuntimeValue="(1)" />

            </ParameterList>





파라메터 스니핑을 못하는 경우 (jTDS)



             <ParameterList>

              <ColumnReference Column="@P0" ParameterRuntimeValue="(1)" />

            </ParameterList>



3) applicationIntent 기능을 MS JDBC 만 지원한다. 4.0 이상부터

고 가용성 기능을 쓰려면 JDBC 로 가야한다. 



기타)

unicode false 옵션은 주의해서 셋팅해라 


Posted by 보미아빠
, |

SQL Server Extended Events (xevent) are great to troubleshoot many issues including performance issues or other targeted scenarios.  But we keep seeing users misusing them to negatively impact their systems.

Here is a latest example.  We had a customer who called our support for an issue where the same query ran fast in test but ran slow in production.  In fact, the query ‘never’ finished in production in a sense that they waited for 30 minutes or more but couldn’t get it to finish.  But the same query finished in seconds in test.

The query was actually a large batch that contains over 90k lines of code with many statements with size of about 800k.   Our initial effort focused on comparing the differences between the two servers.  But there weren’t many differences.   We even eliminated database as a factor. They restored database from production to test and issue went away in test.

Through some troubleshooting, we discovered even parsing the query took a long time in production.    But we simply couldn’t figure out what was going on because the statements in the batch were very simple inserts.   So we took some user dumps and analyzed the call stacks.  Finally we realized that the XEvent was involved.   Every dump we got showed the server was producing XEvent.  It turned out their developers enabled the some xevents which can cause high overhead by accident inproduction.

So we got their Xevents being captured (screen shot below).  Among those, there were scan_started, scan_stopped, wait_info etc.   It was generate a million events every minute without anyone else running the system.  In addition to that, this customer captured sql_text for all the events. Basically the same 800k batch text would be captured for every event including wait_info etc

 

image

 

image

 

None of the events mentioned (scan_started, scan_stopped, wait_info ) are suited for long term capture.   For this specific scenario, it was wait_info that hurt them most (combined with sql_text being included).   Wait_info is produced whenever there is a scheduler yield or wait is finished.    Because customer’s batch is very large, SQL needs to play nice and yields frequently.  so the event gets triggered very frequently.  That’s why so many events were generated and overhead led to slowdown.

 

Demo (tested on SQL Server 2012, 2016)

create and enable Xevents

CREATE EVENT SESSION [test_xevent] ON SERVER
ADD EVENT sqlos.wait_info(
ACTION(package0.collect_system_time,sqlserver.client_app_name,sqlserver.client_hostname,sqlserver.context_info,sqlserver.database_name,sqlserver.nt_username,sqlserver.plan_handle,sqlserver.query_hash,sqlserver.query_plan_hash,sqlserver.session_id,sqlserver.session_nt_username,sqlserver.sql_text)    ),
ADD EVENT sqlos.wait_info_external(
ACTION(package0.collect_system_time,sqlserver.client_app_name,sqlserver.client_hostname,sqlserver.context_info,sqlserver.database_name,sqlserver.nt_username,sqlserver.plan_handle,sqlserver.query_hash,sqlserver.query_plan_hash,sqlserver.session_id,sqlserver.session_nt_username,sqlserver.sql_text)    )
ADD TARGET package0.event_counter,
ADD TARGET package0.event_file(SET filename=N’c:\temp\test_xevent.xel’)
WITH (MAX_MEMORY=4096 KB,EVENT_RETENTION_MODE=ALLOW_SINGLE_EVENT_LOSS,MAX_DISPATCH_LATENCY=30 SECONDS,MAX_EVENT_SIZE=0 KB,MEMORY_PARTITION_MODE=NONE,TRACK_CAUSALITY=ON,STARTUP_STATE=ON)
GO

alter event session [test_xevent] on server state = start

 

in SSMS, duplicate “INSERT INTO t VALUES  (null,null,null)” 50,000 times and try parsing the query.  it will take several minutes.  but if you disable the Xevent session, the entire batch will parse in seconds.

 

If you have to capture wait_info for large batch like this one, consider taking out sql_text.   It will be hard to look at the trace afterwards without it.  But hopefully, it is a controlled environment and you know which session you are troubleshooting and filter on that.

 

Jack Li |Senior Escalation Engineer | Microsoft SQL Server

twitter| pssdiag |Sql Nexus

Posted by 보미아빠
, |

ssma mysql

카테고리 없음 / 2016. 4. 5. 17:48

https://blogs.msdn.microsoft.com/ssma/2011/02/07/mysql-to-sql-server-migration-how-to-use-ssma/


MySQL to SQL Server Migration: How to Use SSMA



By Bill Ramos, Advaiya

[Updated 2/6/2012 Han Wong – Microsoft SQL Server Migration Assistant (SSMA) for MySQL v5.2.  The information provided below is still valid for SSMA for MySQL v5.2.  Users should download the lastest SSMA for MySQL]

In this blog, I’m going to walk you through the process of converting the MySQL Sakila-DB sample database to SQL Server 2008 R2 Express using the SQL Server Migration Assistant for MySQL v1.0 [Updated:  Please obtain the lastest SSMA for MySQL] (SSMA). The Sakila-DB database has tables, views, stored procedures, functions and triggers that make the conversion interesting. The sample is based on the Inno-DB example, but does have one MyISAM table. SSMA also allows you to migrate your MySQL databases to SQL Azure, but we’ll save that topic for another post.

Downloading SQL Server 2008 R2 Express and SSMA

The easiest way to download SQL Server 2008 R2 Express, SQL Server Management Studio and SSMA is through the Microsoft Web Platform Installer (WPI). Once you’ve downloaded WPI, you can select from a variety of tools and products that can get you up and running using IIS, PHP, and SQL Server in no time.

00 Web Platform Installer

I’ll focus on the minimum set of tools you need to get SQL Server 2008 R2 Express and SSMA up and running. once you launch WPI, click on the Products tab at the top tool and then select Database in the navigation page. In the image above, I’ve already installed the tools, but for the new install, you’ll click on the Add buttons to the right of the circled products to get you up and running. If you are running your application under PHP, you might also want to select one of the two PHP drivers for SQL Server as well. Once you’ve selected your tools, just click on the install button to start the process.

Downloading the MySQL ODBC Driver

WPI is not without flaws. SSMA requires the “MySQL OSBC Driver 5.1 or above” download to connect to your MySQL instance that comes from the MySQL downloads site. Once at the Download Connector/ODBC page, your need to download either the x32 or x64 version of the driver based on the machine architecture for the system you are running the SSMA client. Just follow the installation instructions from the installer. The default installation settings will be good enough to get you going.

Other Helpful Downloads for SSMA and this Blog

You’ll also want to download the “Guide to Migrating from MySQL to SQL Server 2008” white paper, though this blog and others to follow will keep you on track.

If you don’t already have the Sakila-DB database for MySQL installed, the link to the download and instructions for installing it can be found at the blog post titled “Learn MySQL With Sakila sample Mysql Database

Using SSMA for MySQL

SQL Server Migration Assistant (SSMA) 2008 for MySQL lets you quickly convert MySQL database schemas to SQL Server 2008, SQL Server 2008 R2 or SQL Azure schemas, upload the resulting schemas the target instance and migrate the data using a single tool.

Licensing SSMA

SSMA is a free tool, but does require you to associate a Microsoft Live ID for identification purposes. You must download a registration key. To help you with the registration process, a License Key Required dialog box opens the first time that you start the SSMA program. Use the following instructions to download a license key and associate the key with SSMA.

To license SSMA

  1. Click Start, point to All Programs, point to Microsoft SQL Server Migration Assistant 2008 for MySQL, and then select Microsoft SQL Server Migration Assistant 2008 for MySQL.

  2. In the License Management dialog box, click the license registration page link.

  3. On the Sign In Web page, enter your Windows Live ID user name and password, and click Sign In.

    A Windows Live ID is a Hotmail e-mail address, MSN e-mail address, or Microsoft Passport account. If you do not have one of these accounts, you will have to create a new account. To create a new account, click the Sign up now button.

  4. On the SQL Server Migration Assistant for MySQL License Registration Web page, fill in at least the required fields, which are marked with a red asterisk, and then click Finish.

  5. In the File Download dialog box, click Save.

  6. In the Save As dialog box, locate the folder that is shown in the License Management dialog box, and then click Save.

    The default location is C:\Documents and Settings\user name\Application Data\Microsoft SQL Server Migration Assistant\m2ss.

  7. In the License Management dialog box, click Refresh License.

SSMA for MySQL User Interface

After SSMA is installed and licensed, you can use SSMA to migrate MySQL databases to SQL Server 2008 or SQL Azure. It helps to become familiar with the SSMA user interface before you start. The following diagram shows the user interface for SSMA, including the metadata explorers, metadata, toolbars, output pane, and error list pane:

01 SSMA MySQL UI OverviewS

Basic Steps for Migration of MySQL to SQL Server

To start a migration, you’ll need to perform the following high level steps:

  1. Create a new project.

  2. Connect to a MySQL database.

  3. After a successful connection, MySQL schemas will appear in MySQL Metadata Explorer. Right-click objects in MySQL Metadata Explorer to perform tasks such as create reports that assess conversions to SQL Server 2008 R2 Express. You can also perform these tasks by using the toolbars and menus.

You’ll then connect to your instance of SQL Server 2008 R2 Express. After a successful connection, a hierarchy of your existing databases will appear in SQL Server Metadata Explorer. After you convert MySQL schemas to SQL Server schemas, select those converted schemas in SQL Server Metadata Explorer, and then synchronize the schemas with SQL Server.

After you synchronize converted schemas with SQL Server 2008 R2 Express, you can return to MySQL Metadata Explorer and migrate data from MySQL schemas into target database.

Let’s walk through the specifics.

Create a MySQL Migration Project

To get started, you’ll create your new project using the File | New Project command.

02 Create Project

You’ll enter in your project name and then confirm that you are migrating to SQL Server. The Migrate To dropdown also allows you to choose SQL Azure, but that’s for another post. Once you make your selection, you are locked into the target backend.

Connect to a MySQL Database

To Connect to your MySQL instance, you’ll issue the File | Connect to MySQL command or click on the tool bar button that launches the following dialog:

03 Connect to MySQL

If you forgot to to install the MySQL ODBC driver mentioned at the beginning of this blog, simply go to the download site, install the driver, and then issue the Connect to MySQL command.

Create Report of Potential Conversion Issues

Once you are connected, you’ll see the MySQL instance in the MySQL Metadata Explorer. You’ll want to expand the Databases node along with the Sakila database node and then check the box next to Sakila. This selects the database you want to migrate. Next, right click on the Sakila database and select the Create Report command or press the Create Report command on the toolbar as shown below.

04 Create Report

Here is an example of the Assessment Report for the Sakila database.

05 Assessment Report

The Assessment Report window contains three panes:

  • The left pane contains the hierarchy of objects that are included in the assessment report. You can browse the hierarchy, and select objects and categories of objects to view conversion statistics and code.

  • The content of the right pane depends on the item that is selected in the left pane.

    If a group of objects is selected, such as schema, the right pane contains a Conversion statistics pane and Objects by Categories pane. The Conversion Statistics pane shows the conversion statistics for the selected objects. The Objects by Categories pane shows the conversion statistics for the object or categories of objects.

    If a function, procedure, table or view is selected, the right pane contains statistics, source code, and target code.

    • The top area shows the overall statistics for the object. You might have to expand Statistics to view this information.

    • The Source area shows the source code of the object that is selected in the left pane. The highlighted areas show problematic source code.

    • The Target area shows the converted code. Red text shows problematic code and error messages.

  • The bottom pane shows conversion messages, grouped by message number. You can click Errors, Warnings, or Info to view categories of messages, and then expand a group of messages. Click an individual message to select the object in the left pane and display the details in the right pane.

In future blog posts, we’ll work through the specific problems that are in this report. For now, we’ll ignore the problematic objects for the schema and data migration steps. For now, close the report and then uncheck Functions, Procedures and Views nodes to take them out of the conversion. Then uncheck the tables with errors as shown below.

06 Ignore Errors

Go ahead and click on the Create Reports command to verify that there are no errors.

Connect to SQL Server

It’s time to connect SSMA to your SQL Server 2008 R2 Express instance. For the Server name, you’ll need the server name and instance for the target server. Since we are using the WPI installation of SQL Server 2008 R2 Express, you’ll enter in the server name as .\SQLEXPRESS.

You can select an existing database to migrate to using the Database control. You can also type in the name of a new database. In this case, use Sakila as shown below.

07 Connect to SQL Server

Once you click connect, SSMA prompts you if you want to create the database. Choose Yes to create the new database. When connecting to SQL Server Express instances, you’ll receive the following warning indicating that you won’t be able to use the server-side data migration engine. This engine is used for larger migration projects.

08 No SQL Agent

You can Continue from this dialog to start the actual migration process.

Convert Schema

Now that you’ve connected to the target SQL Server instance, SSMA enables the Convert Schema command. Click the Convert Schema command. Once the conversion is finished, you should see the SQL Server Metadata Explorer populated with the tables listed in bold as shown below.

09 Convert schema

Synchronize with Database

To write the tables to the target, select the dbo node in the SQL Server Metadata Explorer and then issue the Tools | Synchronize with Database command. SSMA displays the Synchronize with Database dialog as shown below. In this example, the Tables node was manually expanded to show that no tables are actually on the database at this time.

10 Sync with database

When you click OK, SSMA issues the CREATE TABLE statements to create the objects on the SQL Server target. There are some errors in this example because many of the tables selected have foreign key relationships to some of the tables that we excluded earlier. These errors can be ignored for now.

Migrate Data

The last step is to migrate the data into the tables. To complete the migration, select the Tables node within the MySQL Metadata Explorer for the Sakila database. Then issue the Tools | Migrate Data command or press the command on the toolbar. The Data Migration process requires you to connect to the MySQL database and to the SQL Server database again. SSMA then proceeds with the data migration process and displays the Data Migration Reports as shown below.

11 Migrate Data

Using SQL Server Management Studio

The migrated tables are now ready on the target SQL Server instance. To see the results, launch SQL Server Management Studio (SSMS) and connect using the server name as .\SQLEXPRESS. Expand out the Databases node to see the Sakila database. Expand the out the Sakila database tables and then right click on the actor table and issue the Select Top 1000 Rows command to view the data as shown below.

12 Verifying the results

SQL Server Management Studio that is part of the WPI is a free rich Windows client tool from Microsoft that offers a rich development and management experience like  SQLyog and MONyog.

BIO

Bill Ramos is the SQL Server Work Stream Manager for Advaiya. During his 15 years at Microsoft as a program manager, he has been on teams that have shipped the following products: Project Houston, SQL Server 2008 R2, SQL Server 2008, SQL Server 2005, SQL Server 2000, SQL Server 7.0, SQL Server 6.5, Ashton-Tate/Microsoft SQL Server for OS2 (at Ashton-Tate), Excel 2003, Access 2003, Access XP, Access 2000. You can find his personal blog at http://blogs.msdn.com/billramo and on Twitter at http://twitter.com/billramo.




Comments (29)

  1. Curtis says:

    Thank you for this.  I've been banging my head against SSMA on and off for a few days.  I followed your walk-through and data migrated perfectly.

  2. wie setzt man andere Verzeichnisse bei der migration says:

    leider wird bei der migration alles in das standart verzeichnis des sql servers geschrieben, wie ändere ich die Ziele pro datenbank?

  3. Thank you for your valuable article, I want to ask you about a issue is that when I give “Migrate Data” Command. it gives a problem. As you have put a screen where we can see Data Migration Report. I have got same report but without "To and other Column data". it shows only "From" column data.

  4. Fernando says:

    una duda se puende migrar los procedimiento de mysql a sql server 2008 ? es que necesito migrar la base de datos pero tengo mas de 200 procedimientos y quiero cambiarme a sql server

  5. Atit says:

    Hello,

    I am unable to create convert schema after connecting to SQL Server.The convert schema option is deactivated..Should the name of MYSQL database and SQL Server database be the same?? Pls help

  6. PDS says:

    Hi,

    I am trying convert SQl statements from MySql to MS Sql using SSMA but getting error that SSMA ERROR: Unparsed Sql.

    I am adding sql in Statements and then generating report and getting thsi error.

    Thanks

  7. GMM says:

    PDS

    I got the unparsed sql error when I tried to migrate some views. The account I was using on MySQL did not have access to the SQL statements in the view in the schema, so all that showed for those views in SSMA on the SQL tab was a blank screen. I started a new project using a different account which had access to the SQL, then it worked.

    I guess you have to check that the account has access to the SQL statements, and also that the SQL can be parsed. I did this in MySQL Query browser, open the schema, check you can run the SQL.

  8. ravi says:

    Hi,

    Newbie Question! Once the data is migrated does it mean that the data will not be available in Mysql Database ?

  9. Kingmhar says:

    I will try this =D im off to mysql due to limitation =D

  10. Soner CAKIR says:

    Hi,

    Thanks for this article it's really helpfull, but when i try to create a report software returns this error "An unexpected error occurred. Please send the log file to product support. For more information, see "Getting SSMA Assistance" in the product documentation." Windows 7 32 Bit and ODBC Version is 5.1.8, any idea about how i can solve it ?

  11. Doug says:

    Is it possible to get a license for SSMA for a machine without an internet connection?

  12. Martin says:

    Try ESF Database Migration Toolkit

    http://www.easyfrom.net/

  13. Alternatively you can automate your migration/ sync job using

    convertdb.com/…/mssql

  14. When I try to connect to a MySQL database, I put 'root' or some other account name for the username. But when I try to connect, SSMA adds an '@192.168.1. to the end of my username and then access is denied. How do you stop it from adding the dang @my-local computer info? I can't seem to stop if from doing this. Does this thing allow you to connect to remote computers?

  15. Tim McKay says:

    The link in the SSMA app to the page to get the license key is not found… 404 error.

  16. Christopher Deutsch says:

    The registration page is gone. I hope who ever came up with the stupid idea to get a license this way got fired.

  17. Ajay says:

    Hey Chris,

    I understand your FRUSTRATION. Please reach out to Microsoft Support via the link :

    support.microsoft.com/…/default.aspx

    I bet you will get excellent response from this team !

    Regards,

    Ajay

  18. Paul says:

    Do, any of you guys have a license have a license file that can be used since the page is down and Microsoft is a nightmare to get support from?

    Cheers

  19. Mohamed Mamdoun says:

    Hello ,

    Thanks for the post but

    There is a big problem in the license in the SSMA for MYSQL which Microsoft didn't fix until now .

    The link to the license refer to a page that doesn't exist .

    social.msdn.microsoft.com/…/licence-page-for-microsoft-sql-server-migration-assistant-mysql-missing

  20. Jill McClenahan says:

    Thanks for bringing this to our attention.  We have fixed the fwlink to point to a download for the license file.  The direct download link is http://www.microsoft.com/…/details.aspx.

  21. Jagadeesh says:

    Thanks much….. it really helped me to complete the migration from mysql to sql server

  22. mmniet says:

    Came u with a problem which was hard to search for on the internet (and didn't find a solution for). We have a lot of comment in the tables for fields to describe the columns, but SSMA isn't able to migrate them to sql-server. How to fix this problem? Manually is a hell of a job. Please send me a gmail, my account is my used name for this post. Thank you very much!

  23. RJ says:

    When I covert schema the foreign key relationships are maintained, but after I migrate data the foreign keys gets lost.. Any ideas on why this might be happening?

    Thanks

  24. Naveed says:

    i have installed Mysql Administrator v1.2.2 beta. Now when I start to make the new Schema it give me the message that you cannot create the database and shows an error 404 ; Please help me How can I solve it.

  25. muyideen says:

    please i have downloaded the migration assistant, but it will not recognise the odbc for 5.1,5.2 0r 5.3 that i downloaded in various form 0f 32 or 64 bits, please what can i do, i am using windows 7 64 bit  thanks

  26. mir safi says:

    Hi I am currently migrating data from mysql to SQL and i am using SSMA.

    I have successfully connected MySQL and SQL and when i am trying to convert the Schema i get an error stating " An unexpected error occurred. Please send the log file to product support. For more information, see "Getting SSMA Assistance" in the product documentation. Object reference not set to an instance of an object."

    Please help me unable to sort this and I am stuck in this from past few days.

  27. iain says:

    I followed all the steps and the data failed to migrate at the very last step – telling me in the report that it, well, that it failed to migrate.

  28. Klein says:

    Newbie Question! Once the data is migrated does it mean that the data will not be available in Mysql Database ? http://www.dauthu-dvbt2.com


Posted by 보미아빠
, |

mstsc shadow:2

카테고리 없음 / 2016. 3. 28. 14:50

mstsc shadow:2

ssd smart path


Posted by 보미아빠
, |

메모리 관련

카테고리 없음 / 2016. 3. 25. 12:12

https://support.microsoft.com/en-us/kb/2160852

Posted by 보미아빠
, |

tcp-ip

카테고리 없음 / 2016. 3. 22. 18:13

https://blogs.technet.microsoft.com/koalra/2012/01/15/30-windows-server-51/

Posted by 보미아빠
, |

ag readonly

카테고리 없음 / 2016. 3. 22. 10:03


http://www.overtop.co.kr/136




가용성 그룹에 대한 읽기 전용 라우팅 구성(SQL Server)
Configure Read-Only Routing for an Availability Group
https://msdn.microsoft.com/library/hh710054.aspx

읽기전용 라우팅을 언제 사용해야 적절할까는 고민할 부분이다.

 

[환경]

AG1㈜, AG2(보조), AG3(보조) 의 복제복이 존재한다.

[Action Plan]

A. 필수 구성 요소

가용성 그룹 수신기 있어야 한다.

읽기전용 보조 복제복이 있어야 한다.

B. 적용은 T-SQL 또는 PowerShell 로만 적용이 가능하다.

 

 

 

-- 1. 읽기전용 라우팅 설정 하기

/*

읽기전용이란 이름으로 정의하였기 때문에 보조복제본의 연결은 모두 ALL 이 아닌 READ_ONLY 이어야 한다.

아래 설정변경은 주복제본에서만 수행이 된다.

*/

use master

go

 

ALTER AVAILABILITY GROUP AGName

MODIFY REPLICA ON N'AG1' WITH (SECONDARY_ROLE(ALLOW_CONNECTIONS = READ_ONLY))

 

ALTER AVAILABILITY GROUP AGName

MODIFY REPLICA ON N'AG2' WITH (SECONDARY_ROLE(ALLOW_CONNECTIONS = READ_ONLY))

 

ALTER AVAILABILITY GROUP AGName

MODIFY REPLICA ON N'AG3' WITH (SECONDARY_ROLE(ALLOW_CONNECTIONS = READ_ONLY))

 

ALTER AVAILABILITY GROUP AGName

MODIFY REPLICA ON

N'AG1' WITH

(SECONDARY_ROLE (READ_ONLY_ROUTING_URL = N'TCP://AG1.overtop.local:1433'));

 

ALTER AVAILABILITY GROUP AGName

MODIFY REPLICA ON

N'AG2' WITH

(SECONDARY_ROLE (READ_ONLY_ROUTING_URL = N'TCP://AG2.overtop.local:1433'));

 

ALTER AVAILABILITY GROUP AGName

MODIFY REPLICA ON

N'AG3' WITH

(SECONDARY_ROLE (READ_ONLY_ROUTING_URL = N'TCP://AG3.overtop.local:1433'));

 

 

ALTER AVAILABILITY GROUP AGName

MODIFY REPLICA ON

N'AG1' WITH

(PRIMARY_ROLE (READ_ONLY_ROUTING_LIST=('AG2','AG3','AG1')));

-- AG1 이 주 복제본일경우에 라우팅은 AG3 로 연결되며, AG3 가 접속이 안되는 경우에는 AG2 로 자동연결 된다.

 

ALTER AVAILABILITY GROUP AGName

MODIFY REPLICA ON

N'AG2' WITH

(PRIMARY_ROLE (READ_ONLY_ROUTING_LIST=('AG3','AG1','AG2')));

 

ALTER AVAILABILITY GROUP AGName

MODIFY REPLICA ON

N'AG3' WITH

(PRIMARY_ROLE (READ_ONLY_ROUTING_LIST=('AG1','AG2','AG3')));

GO

 

 

-- 2. 설정 확인하기.

SELECT * FROM sys.availability_read_only_routing_lists

GO

 

SELECT ag.name as "Availability Group", ar.replica_server_name as "When Primary Replica Is",

rl.routing_priority as "Routing Priority", ar2.replica_server_name as "RO Routed To",

ar.secondary_role_allow_connections_desc, ar2.read_only_routing_url

FROM sys.availability_read_only_routing_lists rl

inner join sys.availability_replicas aon rl.replica_id = ar.replica_id

inner join sys.availability_replicas ar2 on rl.read_only_replica_id = ar2.replica_id

inner join sys.availability_groups ag on ar.group_id = ag.group_id

ORDER BY ag.name, ar.replica_server_name, rl.routing_priority

 

 

C. 라우팅 연결 테스트

-K , -d 옵션을 필수 입력해야 확인이 가능하다.
주 복제본에 따라 라우팅 순서를 정의할 수 있다. 위 코드 상에서 AG2가 주 복제복일경우에는 AG3 리턴한다.

sqlcmd -S Aglistener.overtop.local,62000 -E -K ReadOnly -d AGDB1 -Q "select @@servername"

 

 

[참고문서]

Modifying AlwaysOn Read Only Routing Lists
http://blogs.msdn.com/b/alwaysonpro/archive/2014/01/22/modifying-alwayson-read-only-routing-lists.aspx




192.168.137.5에 연결하는 중...

메시지 41158, 수준 16, 상태 3, 줄 65

로컬 가용성 복제본을 가용성 그룹 'poc_ag'에 조인하지 못했습니다. 작업 중 SQL Server 오류 41106이(가) 발생하여 작업이 롤백되었습니다. 자세한 내용은 SQL Server 오류 로그를 확인하십시오. 나중에 오류 원인을 해결한 후 ALTER AVAILABILITY GROUP JOIN 명령을 다시 시도하십시오.

192.168.137.5에서 연결을 끊는 중...

주서버에서 transaction log backup 후 보조서버에서 norecovery 로 복구 후 조인하면 된다. 


쿼럼 구성



클라이언트가 ad 도메인에 없을경우 


클라이언트의 host 에 도메인 이름을 명시적으로 쓰던지 

아래와 같이 리스너 구성을 명시적으로 ip 를 기술한다. 



ALTER AVAILABILITY GROUP poc_ag

MODIFY REPLICA ON N'mhv1' WITH (SECONDARY_ROLE(ALLOW_CONNECTIONS = READ_ONLY))


ALTER AVAILABILITY GROUP poc_ag

MODIFY REPLICA ON N'mhv2' WITH (SECONDARY_ROLE(ALLOW_CONNECTIONS = READ_ONLY))


ALTER AVAILABILITY GROUP poc_ag

MODIFY REPLICA ON N'chv1' WITH (SECONDARY_ROLE(ALLOW_CONNECTIONS = READ_ONLY))


 


ALTER AVAILABILITY GROUP poc_ag

MODIFY REPLICA ON

N'mhv1' WITH (SECONDARY_ROLE (READ_ONLY_ROUTING_URL = N'TCP://192.168.137.4:1433'));


ALTER AVAILABILITY GROUP poc_ag

MODIFY REPLICA ON

N'mhv2' WITH (SECONDARY_ROLE (READ_ONLY_ROUTING_URL = N'TCP://192.168.137.5:1433'));


ALTER AVAILABILITY GROUP poc_ag

MODIFY REPLICA ON

N'chv1' WITH (SECONDARY_ROLE (READ_ONLY_ROUTING_URL = N'TCP://192.168.137.6:1433'));


 


 


ALTER AVAILABILITY GROUP poc_ag

MODIFY REPLICA ON

N'mhv1' WITH

(PRIMARY_ROLE (READ_ONLY_ROUTING_LIST=('chv1','mhv2','mhv1')));

-- AG1 이 주 복제본일경우에 라우팅은 AG3 로 연결되며, AG3 가 접속이 안되는 경우에는 AG2 로 자동연결 된다.


ALTER AVAILABILITY GROUP poc_ag

MODIFY REPLICA ON

N'mhv2' WITH

(PRIMARY_ROLE (READ_ONLY_ROUTING_LIST=('chv1','mhv1','mhv2')));


ALTER AVAILABILITY GROUP poc_ag

MODIFY REPLICA ON

N'chv1' WITH

(PRIMARY_ROLE (READ_ONLY_ROUTING_LIST=('mhv2','mhv1','chv1')));

GO





jdbc test







package com.company;
import java.sql.*;
public class Main {

public static void RunQuery() throws ClassNotFoundException, SQLException, InterruptedException
{

String url = "jdbc:sqlserver://192.168.137.44;DatabaseName=cafedb;ApplicationIntent=ReadOnly";
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
conn = DriverManager.getConnection(url, "test", "1234!@#$");
stmt = conn.createStatement();
rs = stmt.executeQuery("select @@servername ServerName");

rs.next();
System.out.println(rs.getString("ServerName"));
Thread.sleep(500);

rs.close();
stmt.close();
conn.close();
}

public static void main(String[] args)
{
Integer i = 0;
while (1 == 1)
{
i++;
try
{
Main.RunQuery();
System.out.println(i);
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}
}



Posted by 보미아빠
, |

10퍼센트 처리되었습니다.

20퍼센트 처리되었습니다.

30퍼센트 처리되었습니다.

40퍼센트 처리되었습니다.

50퍼센트 처리되었습니다.

60퍼센트 처리되었습니다.

70퍼센트 처리되었습니다.

80퍼센트 처리되었습니다.

90퍼센트 처리되었습니다.

100퍼센트 처리되었습니다.

파일 1에서 데이터베이스 'userDatabase', 파일 'userDatabase_Data'에 대해 0개의 페이지를 처리했습니다 .

파일 1에서 데이터베이스 'userDatabase', 파일 'userDatabase_Data2'에 대해 0개의 페이지를 처리했습니다 .

파일 1에서 데이터베이스 'userDatabase', 파일 'userDatabase_Data3'에 대해 0개의 페이지를 처리했습니다 .

파일 1에서 데이터베이스 'userDatabase', 파일 'userDatabase_GUEST'에 대해 0개의 페이지를 처리했습니다 .

파일 1에서 데이터베이스 'userDatabase', 파일 'userDatabase_z1'에 대해 0개의 페이지를 처리했습니다 .

파일 1에서 데이터베이스 'userDatabase', 파일 'userDatabase_Log'에 대해 234355개의 페이지를 처리했습니다 .

메시지 3456, 수준 16, 상태 1, 줄 1

페이지 (1:828275), 데이터베이스 'userDatabase'(데이터베이스 ID 5)에서 트랜잭션 ID (16:395253956)에 대한 로그 레코드 (3529369:96028:38)을(를) 다시 실행할 수 없습니다. 페이지: LSN = (3529369:95946:19), 유형 = 2. 로그: OpCode = 3, 컨텍스트 19, PrevPageLSN: (3529369:95244:5). 데이터베이스 백업에서 복원하거나 데이터베이스를 복구하십시오.

메시지 9004, 수준 16, 상태 6, 줄 1

데이터베이스 'userDatabase'의 로그를 처리하는 동안 오류가 발생했습니다. 가능하면 백업을 사용하여 복원하십시오. 백업이 없을 경우 로그를 다시 만들어야 합니다.

메시지 3013, 수준 16, 상태 1, 줄 1

RESTORE LOG이(가) 비정상적으로 종료됩니다.


다음 로그를 더 복구할 수 없다. 



내용을 보니 현재 처리중인 LSN (3529369:95946:19) 과 이전 LSN (3529369:95244:5) 이 맞지 않아 나는 에러인데....왜 이런 현상이 일어나는지는 이해할 수 없네...


테스트가 필요한 부분은 데이터베이스 커럽션이 있는지

차등백업 후 로그백업을 복구하면 에러없이 진행 가능한지 등이 있겠다. 

최후의 수단으로 CONTINUE_AFTER_ERROR 가 있을 수 있다. 


읽어볼만한 글

http://dba.stackexchange.com/questions/93473/unable-to-restore-error-3456

https://social.msdn.microsoft.com/Forums/sqlserver/en-US/36dd0107-ceca-4d48-8523-3c5624c135b2/msg-3456-level-16-state-1-could-not-redo-log-record?forum=sqldatabaseengine

https://www.mssqltips.com/sqlservertip/3209/understanding-sql-server-log-sequence-numbers-for-backups/


복사본

In order to understanding why error 3456 would be thrown, we need to take a little step back and understand how SQL Server handles this corner of recovery.

When SQL Server is redoing an operation, and that redo is a page modification, it makes a quick check. In the page header there is ultimately going to be a PageLSN, which is an indication of the last LSN that has modified that page, recorded by the page. Think about it like this, the page keeps track of the last LSN that has made modifications to it. This is the PageLSN.

Every time there is a logged page modification operation, that log record includes a few LSNs. Namely, the log record's LSN (think... Current LSN), and then it has what's called the Previous Page LSN (PrevPageLSN going forward). So when we modify a page, one of the pieces of data that is put into the log record is what the page indicates as being the last LSN before you to have modified the page.

Think about it like this... Your car needs to have work done on it. Mechanic John works on your car, and in the engine bay it has a little tag and Mechanic John writes "John worked on this car last". Then the next time you take your car in to another shop, Mechanic Mark looks in the engine bay and sees that Mechanic John worked on this car last. On his data sheet he writes this information. Same idea with SQL Server.

This can be somewhat confusing, so take a look at this image below on sequential page modifications, and how the PageLSN and PrevPageLSN relate:

enter image description here

Let's loop back around, as this all comes into play when you need to redo an operation on a page (restores, recovery, HA, etc.). When SQL Server needs to redo a page operation, it makes a sanity check to see if the PageLSN on the page matches the PrevPageLSN that the log record includes. If that is not equal, then you will see error 3456 get thrown.

Does PageLSN equal PrevPageLSN? No??? Stop and raise error 3456...

Let's analyze your error message, which includes the how:

Could not redo log record (210388:123648:232), for transaction ID (0:1016710921), on page (4:8088), database 'SomeDB' (database ID 6). Page: LSN = (0:0:1), type = 11. Log: OpCode = 4, context 11, PrevPageLSN: (210388:122007:1). Restore from a backup of the database, or repair the database. Msg 3013, Level 16, State 1, Line 1 RESTORE LOG is terminating abnormally.

I have bold'd the two pieces of data that have an inequality causing the error. You can see that our PageLSN is 0:0:1 (this was found in the page's header), and our PrevPageLSN is 210388:122007:1(this was found in the data on the log record that was attempting to be redone). These are obviously not equal, hence err3456.

So in order to find out the why of this event, would be to find out why there is a disparity here. We really need to trace the lifecycle of page 4:8088 and see where the disconnect is. Unfortunately without further information, or hands-on troubleshooting there isn't much else I can do besides give you the background of this recovery operation and what causes the error.

shareimprove this answer







Problem

This tip describes SQL Server Log Sequence Numbers (LSNs) and how the sequence numbers link full, differential and transaction log backups.  We will look at sample backups and how these LSN values can be read from the backup files to determine the restore path.

Solution

This tip is the continuation from this tip, Different Ways to Restore a SQL Server Database, and utilizes the same database creation and backup scripts to explain how the SQL Server full, differential and transaction log backup chain is mapped between each backup type. If you want to follow along, please read this first tip and setup your database and backups.

RESTORE HEADERONLY

When restoring a database, the initial database RESTORE sequence must begin from a FULL database backup. A database RESTORE sequence cannot begin with a differential file backup or transaction log backup. When restoring databases there are four important LSNs: FirstLSN, LastLSN, CheckpointLSN and DatabaseBackupLSN.  These values can be retrieved from a SQL Server backup file using the RESTORE HEADERONLY command.

You can use RESTORE HEADERONLY to retrieve the backup header information for each backup file on disk as shown below.

USE [master]
RESTORE HEADERONLY FROM DISK = N'C:\Temp\F1.BAK'
RESTORE HEADERONLY FROM DISK = N'C:\Temp\T1.TRN'
RESTORE HEADERONLY FROM DISK = N'C:\Temp\T2.TRN'
RESTORE HEADERONLY FROM DISK = N'C:\Temp\D1.BAK'



SQL Server Log Sequence Numbers (LSNs)

I have collated the FirstLSN, LastLSN, CheckpointLSN and DatabaseBackupLSN for these database backup files (Database setup script) into an Excel spreadsheet as shown below. The full scripts to retrieve the LSNs from all backup files are found at the end of this tip.

"Column A" is the backup type performed at a point-in-time (i.e. F1 = first full backup, T3 = third transaction log backup, D2 = second differential backup).

The full scripts to retrieve LSNs from all backup files are found at the end of this tip. “Column A” is backup type performed at a point-in-time.

Some attributes for the full database backup LSNs are:

  •  The very first full database backup will always have a DatabaseBackupLSN of zero
  •  The very first full database backup's FirstLSN will be the same as the CheckpointLSN

Some attributes of a differential database backup LSNs are:

  • The DatabaseBackupLSN value for the differential backup identifies the full database backup that is required in order to apply the differential database backup
  • The DatabaseBackupLSN value for the differential backup will match its base full database backup CheckpointLSN
  • The CheckpointLSN maps to the CheckpointLSN of the first transaction log backup after the differential backup

Some attributes of a transaction log backup LSNs are:

  • A LSN uniquely identifies every record in a transaction log backup
  • The FirstLSN and CheckpointLSN of the first transaction log backup is also the first full database backup CheckpointLSN if the backup is taken when the database is idle and no replication is configured
  • The transaction log LSN chain is not affected by a full or differential database backup
  • LSN are sequential in nature. A higher LSN value indicates a later point in time

Understanding LSN Mapping Examples in SQL Server

Below are 3 sections that describe the LSN mapping for:

  • Full database backup LSN to Transaction Log backup LSN
  • Full database backup LSN to Differential database backup LSN
  • Differential database backup LSN to Transaction Log backup LSN

Full database backup LSN to Transaction Log backup LSN

Full database backup LSN – Transaction Log backup LSN
  • FirstLSN identifies the first log record included in the backup
  • LastLSN includes log records up to, but not including this LSN
  • When planning which transaction log backup to use to roll forward, the LastLSN + 1 of the Full database backup will fall in between the FirstLSN and LastLSN of its subsequent transaction log backup
  • In the example above, Full database backup LastLSN 34000000025600001 falls in between transaction log backup T1 FirstLSN 34000000016000100 and LastLSN 34000000028800000. Applying T1 after F1 will succeed, applying T2 or T3 after F1 will result in an error.
  • A transaction log backup's LastLSN is the FirstLSN in the subsequent transaction log backup chain. In the example above, transaction log backup T1 LastLSN 34000000028800000 is the FirstLSN of transaction log backup T2, transaction log backup T2 LastLSN 34000000030400000 is the FirstLSN of transaction log backup T3 and so on

Full database backup LSN to Differential database backup LSN

Full database backup LSN - Differential database backup LSN
  • A differential database backup can only be applied ONCE to a restored full database backup that has a CheckpointLSN value that is equal to the differential backup DatabaseBackupLSN

Differential database backup LSN to Transaction Log backup LSN

Differential database backup LSN – Transaction Log backup LSN
  • A differential backup LastLSN + 1 will be in between the FirstLSN and LastLSN of its subsequent transaction log backup
  • In the example above, Full database backup LastLSN 34000000035200001 falls in between transaction log backup T3 FirstLSN 34000000030400000 and LastLSN 34000000036000000. Applying T3 after D1 will succeed, applying T4 or another transaction log backup will result in an error.

Script to Retrieve Backup LSNs

This is the full script to retrieve the LSNs for all database backup files created from this tip.

USE [master]
RESTORE HEADERONLY FROM DISK = N'C:\Temp\F1.BAK'
RESTORE HEADERONLY FROM DISK = N'C:\Temp\T1.TRN'
RESTORE HEADERONLY FROM DISK = N'C:\Temp\T2.TRN'
RESTORE HEADERONLY FROM DISK = N'C:\Temp\D1.BAK'
RESTORE HEADERONLY FROM DISK = N'C:\Temp\T3.TRN'
RESTORE HEADERONLY FROM DISK = N'C:\Temp\T4.TRN'
RESTORE HEADERONLY FROM DISK = N'C:\Temp\D2.BAK'
RESTORE HEADERONLY FROM DISK = N'C:\Temp\T5.TRN'
RESTORE HEADERONLY FROM DISK = N'C:\Temp\F2.BAK'
RESTORE HEADERONLY FROM DISK = N'C:\Temp\T6.TRN'
RESTORE HEADERONLY FROM DISK = N'C:\Temp\T7.TRN'
RESTORE HEADERONLY FROM DISK = N'C:\Temp\D3.BAK'
RESTORE HEADERONLY FROM DISK = N'C:\Temp\T8.TRN'
Next Steps



Posted by 보미아빠
, |

최근에 달린 댓글

최근에 받은 트랙백

글 보관함