【SQL Server】【運用】Microsoft SQL Server 2016 の各種情報を取得する手順【Part.18】

公開日時:2019年05月25日 / 最終更新日時:2021年10月10日

Microsoft SQL Server 2016 の各種情報を取得する手順について解説します。

 

 

 

検証環境

以下の「Windows Server 2016」「SQL Server 2016」の日本語環境を利用しました。

 

 

 

コマンドライン(PowerShell)からの SQL Server 接続

コマンドライン(PowerShell)から SQL Server へ接続します。

 

Windows スタートボタンをクリックし「Windows PowerShell」をクリックします。

 

 

 

 

■SQL Server 接続のコマンド

PS C:\Users\Administrator> sqlcmd -S EC2AMAZ-UDKT284,1433 -U sa -P PassWord1234
1>

 

■オプション

 

 

■SQL Server 接続のコマンド(DB を指定する場合)

PS C:\Users\Administrator> sqlcmd -S EC2AMAZ-UDKT284,1433 -U sa -P PassWord1234 -d AdventureWorks2016 
1>

 

■オプション

 

 

■SQL Server 接続のコマンド(カンマ区切りにして且つ DB を指定する場合)

PS C:\Users\Administrator> sqlcmd -S EC2AMAZ-UDKT284,1433 -U sa -P xxxxxxxxxx -d AdventureWorks2016 -W -s ","
1>

 

■オプション

 

 

 

 

データベース一覧を表示する

コマンドラインよりデータベース一覧を表示します。

2> select name from sys.databases; 
3> go 
name 
 
-------------------------------------------------------------------------- 
-------- 
master 
 
tempdb 
 
model 
 
msdb 
 
AdventureWorks2016 
 
 
(5 行処理されました) 
1>

 

 

現在のデータベースを確認する

現在、どのデータベースに接続しているか確認します。

1> select db_name() as [current database]; 
2> go 
current database 
-------------------------------------------------- 
master 
 
(1 行処理されました) 
1>

 

 

 

 

データベースを変更する(指定する)

データベースを変更します。

1> use AdventureWorks2016 
2> go 
データベース コンテキストが 'AdventureWorks2016' に変更されました。 
1> select name from sysobjects where xtype = 'U';

 

 

 

 

 

テーブル一覧を取得する

テーブル一覧を取得します。

1> select name from sysobjects where xtype = 'U'; 
2> go 
name 
 
----------------------------------------------------------------------------------------------------- 
-------- 
SalesTaxRate 
 
PersonCreditCard 
 
PersonPhone 
 
SalesTerritory 
 
PhoneNumberType 
 
Product 
 
SalesTerritoryHistory 
 
ScrapReason 
 
Shift 
 
ProductCategory 
 
ShipMethod 
 
ProductCostHistory 
 
ProductDescription 
 
ShoppingCartItem 
 
ProductDocument 
 
DatabaseLog 
 
ProductInventory 
 
SpecialOffer 
 
ErrorLog 
 
ProductListPriceHistory 
 
Address 
 
SpecialOfferProduct 
 
ProductModel 
 
AddressType 
 
StateProvince 
 
ProductModelIllustration 
 
AWBuildVersion 
 
ProductModelProductDescriptionCulture 
 
BillOfMaterials 
 
Store 
 
ProductPhoto 
 
ProductProductPhoto 
 
TransactionHistory 
 
ProductReview 
 
BusinessEntity 
 
TransactionHistoryArchive 
 
ProductSubcategory 
 
BusinessEntityAddress 
 
ProductVendor 
 
BusinessEntityContact 
 
UnitMeasure 
 
Vendor 
 
ContactType 
 
CountryRegionCurrency 
 
CountryRegion 
 
WorkOrder 
 
PurchaseOrderDetail 
 
CreditCard 
 
Culture 
 
WorkOrderRouting 
 
Currency 
 
PurchaseOrderHeader 
 
CurrencyRate 
 
Customer 
 
Department 
 
Document 
 
SalesOrderDetail 
 
EmailAddress 
 
Employee 
 
SalesOrderHeader 
 
EmployeeDepartmentHistory 
 
EmployeePayHistory 
 
SalesOrderHeaderSalesReason 
 
SalesPerson 
 
Illustration 
 
JobCandidate 
 
Location 
 
Password 
 
SalesPersonQuotaHistory 
 
Person 
 
SalesReason 
 
 
(71 行処理されました) 
1>

 

 

 

 

表示を見やすくする

表示桁数(折り返し位置)を指定してコマンド結果を見やすく設定します。

PS C:\Users\Administrator> sqlcmd -S EC2AMAZ-UDKT284,1433 -U sa -P Password1234 -w 1000
1> 

 

 

表示を見やすくした状態でテーブル一覧を取得します。

横に広がっていますが、テキストエディタで折り返しなしにすると綺麗に表示されます。

1> select * from sysobjects where xtype = 'U'; 
2> go 
name                                                                                                                             id          xtype uid    info   status      base_schema_ver replinfo    parent_obj  crdate                  ftcatid schema_ver  stats_schema_ver type userstat sysstat indexdel refdate                 version     deltrig     instrig     updtrig     seltrig     category    cache 
-------------------------------------------------------------------------------------------------------------------------------- ----------- ----- ------ ------ ----------- --------------- ----------- ----------- ----------------------- ------- ----------- ---------------- ---- -------- ------- -------- ----------------------- ----------- ----------- ----------- ----------- ----------- ----------- ------ 
trace_xe_action_map                                                                                                               -463397375 U          4      0           0               0           0           0 2016-04-30 00:44:47.007       0           0                0 U           1       3        0 2016-04-30 00:44:47.007           0           0           0           0           0           2      0 
trace_xe_event_map                                                                                                                -319884821 U          4      0           0               0           0           0 2016-04-30 00:44:46.937       0           0                0 U           1       3        0 2016-04-30 00:44:46.937           0           0           0           0           0           2      0 
spt_fallback_db                                                                                                                    117575457 U          1      0           0               0           0           0 2003-04-08 09:18:01.557       0           0                0 U           1       3        0 2003-04-08 09:18:01.557           0           0           0           0           0           2      0 
spt_fallback_dev                                                                                                                   133575514 U          1      0           0               0           0           0 2003-04-08 09:18:02.870       0           0                0 U           1       3        0 2003-04-08 09:18:02.870           0           0           0           0           0           2      0 
spt_fallback_usg                                                                                                                   149575571 U          1      0           0               0           0           0 2003-04-08 09:18:04.180       0           0                0 U           1       3        0 2003-04-08 09:18:04.180           0           0           0           0           0           2      0 
spt_monitor                                                                                                                       1483152329 U          1      0           0               0           0           0 2016-04-30 00:46:37.557       0           0                0 U           1       3        0 2016-04-30 00:46:37.557           0           0           0           0           0           2      0 
MSreplication_options                                                                                                             1787153412 U          1      0           0               0           0           0 2016-04-30 00:47:59.690       0           0                0 U           1       3        0 2016-04-30 00:47:59.690           0           0           0           0           0           2      0 
 
(7 行処理されました) 
1> 

 

 

SELECT 文の結果をカンマ区切りで表示させて Excel で分析しやすくする

個人的にはこの方法が一番いいかなと思います。

SELECT 文の結果をカンマ区切りで表示させて Excel で分析しやすくする方法です。

 

sqlcmd コマンドで、-s "," オプションを付けてデータベースに接続します。

PS C:\Users\Administrator> sqlcmd -S EC2AMAZ-UDKT284,1433 -U sa -P Password1234 -W -s ","
1>

 

 

以下のようにカンマ区切りで表示されます。

これを Excel ファイルに貼り付けます。

1> exec msdb.dbo.sp_help_job; 
2> go 
job_id,originating_server,name,enabled,description,start_step_id,category,owner,notify_level_eventlog,notify_level_email,notify_level_netsend,notify_level_page,notify_email_operator,notify_netsend_operator,notify_page_operator,delete_level,date_created,date_modified,version_number,last_run_date,last_run_time,last_run_outcome,next_run_date,next_run_time,next_run_schedule_id,current_execution_status,current_execution_step,current_retry_attempt,has_step,has_schedule,has_target,type 
------,------------------,----,-------,-----------,-------------,--------,-----,---------------------,------------------,--------------------,-----------------,---------------------,-----------------------,--------------------,------------,------------,-------------,--------------,-------------,-------------,----------------,-------------,-------------,--------------------,------------------------,----------------------,---------------------,--------,------------,----------,---- 
5944788C-596C-4CF1-A201-3CA1FE9277F7,EC2AMAZ-UDKT284,syspolicy_purge_history,1,使用できる説明はありません。,1,[Uncategorized (Local)],sa,0,0,0,0,(不明),(不明),(不明),0,2017-03-01 19:53:24.373,2017-03-01 19:53:24.730,5,20190208,20000,1,20190526,20000,8,4,0 (不明),0,3,1,1,1 
1> 

 

 

下図のように Excel ファイルで分析が出来るようになります。

 

 

 

 

-W オプションで空白を削除する

sqlcmd コマンドの場合は、「-W」オプションで空白を削除することができます。

以下の「-W」オプション付きのコマンドでデータベースに接続します。

PS C:\Users\Administrator> sqlcmd -S EC2AMAZ-UDKT284,1433 -U sa -P Password1234 -W
1>

 

コマンドを実行します。

横幅の制限があるため折り返されて見にくいですが、空白は削除されています。

1> exec msdb.dbo.sp_help_job; 
2> go 
job_id originating_server name enabled description start_step_id category owner notify_level_eventlog notify_level_email notify_level_netsend notify_level_page notify_email_operator notify_netsend_operator notify_page_operator delete_level date_created date_modified version_number last_run_date last_run_time last_run_outcome next_run_date next_run_time next_run_schedule_id current_execution_status current_execution_step current_retry_attempt has_step has_schedule has_target type 
------ ------------------ ---- ------- ----------- ------------- -------- ----- --------------------- ------------------ -------------------- ----------------- --------------------- ----------------------- -------------------- ------------ ------------ ------------- -------------- ------------- ------------- ---------------- ------------- ------------- -------------------- ------------------------ ---------------------- --------------------- -------- ------------ ---------- ---- 
5944788C-596C-4CF1-A201-3CA1FE9277F7 EC2AMAZ-UDKT284 syspolicy_purge_history 1 使用できる説明はありません。 1 [Uncategorized (Local)] sa 0 0 0 0 (不明) (不明) (不明) 0 2017-03-01 19:53:24.373 2017-03-01 19:53:24.730 5 20190208 20000 1 20190526 20000 8 4 0 (不明) 0 3 1 1 1 
1> 

 

 

 

 

SQL Server Management Studio を利用できるなら利用した方がクエリ結果を綺麗に表示できる

SQL 文で何とかクエリ結果を整形するのも限界があります。

そのため、SQL Server Management Studio を利用できるなら、利用した方がクエリ結果を綺麗に表示できます。

 

【手順】

  1. SQL Server Management Studio を起動します。
  2. 「新しいクエリ」ボタンをクリックします。
  3. 実行したいクエリを入力します。(goも含めます。)
  4. 「実行」ボタンをクリックします。
  5. クエリ結果が表示されます。

 

 

実行結果を Excel に貼り付けて分析することも簡単です。

クエリ結果を右クリックして「ヘッダー付きでコピー」をクリックします。

 

 

 

下図のように Excel に貼り付けて分析ができます。

 

 

 

ジョブ一覧を表示する

ジョブ一覧です。

横長になり途中で折り返されているため非常に見にくいです。

1> exec msdb.dbo.sp_help_job; 
2> go 
job_id                               originating_server                                                                                                               name                                                                                                                             enabled description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      start_step_id category                                                                                                                         owner                                                                                                                            notify_level_eventlog notify_level_email notify_level_netsend notify_level_page notify_email_operator                                                                                                            notify_netsend_operator                                                                                                          notify_page_operator                                                                                                             delete_level date_created            date_modified           version_number last_run_date last_run_time last_run_outcome next_run_date next_run_time next_run_schedule_id current_execution_status current_execution_step                                                                                                                                                                                                                                           current_retry_attempt has_step    has_schedule has_target  type 
------------------------------------ -------------------------------------------------------------------------------------------------------------------------------- -------------------------------------------------------------------------------------------------------------------------------- ------- -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ------------- -------------------------------------------------------------------------------------------------------------------------------- -------------------------------------------------------------------------------------------------------------------------------- --------------------- ------------------ -------------------- ----------------- -------------------------------------------------------------------------------------------------------------------------------- -------------------------------------------------------------------------------------------------------------------------------- -------------------------------------------------------------------------------------------------------------------------------- ------------ ----------------------- ----------------------- -------------- ------------- ------------- ---------------- ------------- ------------- -------------------- ------------------------ ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- --------------------- ----------- ------------ ----------- ----------- 
5944788C-596C-4CF1-A201-3CA1FE9277F7 EC2AMAZ-UDKT284                                                                                                                  syspolicy_purge_history                                                                                                                1 使用できる説明はありません。                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               1 [Uncategorized (Local)]                                                                                                          sa                                                                                                                                                   0                  0                    0                 0 (不明)                                                                                                                             (不明)                                                                                                                             (不明)                                                                                                                                        0 2017-03-01 19:53:24.373 2017-03-01 19:53:24.730              5      20190208         20000                1      20190526         20000                    8                        4 0 (不明)                                                                                                                                                                                                                                                                               0           3            1           1           1 
1> 

 

 

 

 

ストアドプロシージャの情報を出力する

ストアドプロシージャの各種情報を出力する方法です。

 

ストアドプロシージャの一覧を表示する

ストアドプロシージャの一覧を表示する方法です。

1> SELECT sysobjects.name 
2>       ,sysobjects.crdate 
3> FROM   sysobjects 
4> WHERE  sysobjects.type ='P' 
5> go 
name                                                                                                                             crdate 
-------------------------------------------------------------------------------------------------------------------------------- ----------------------- 
uspGetBillOfMaterials                                                                                                            2017-10-19 17:24:52.267 
uspGetEmployeeManagers                                                                                                           2017-10-19 17:24:52.273 
uspGetManagerEmployees                                                                                                           2017-10-19 17:24:52.280 
uspGetWhereUsedProductID                                                                                                         2017-10-19 17:24:52.283 
uspUpdateEmployeeHireInfo                                                                                                        2017-10-19 17:24:52.287 
uspUpdateEmployeeLogin                                                                                                           2017-10-19 17:24:52.290 
uspPrintError                                                                                                                    2017-10-19 17:24:40.323 
uspUpdateEmployeePersonalInfo                                                                                                    2017-10-19 17:24:52.293 
uspLogError                                                                                                                      2017-10-19 17:24:40.330 
uspSearchCandidateResumes                                                                                                        2017-10-19 17:24:52.297 
 
(10 行処理されました) 
1>

 

 

 

オプション「-s」を追加して、カンマ区切りに変更し Excel に貼り付けて見やすくします。

以下のコマンドでデータベースに接続します。

PS C:\Users\Administrator> sqlcmd -S EC2AMAZ-UDKT284,1433 -U sa -P xxxxxxxxx -d AdventureWorks2016 -W -s ","
1>

 

■オプション

 

1> SELECT sysobjects.name  
2>       ,sysobjects.crdate 
3> FROM   sysobjects 
4> WHERE  sysobjects.type ='P' 
5> go 
name,crdate 
----,------ 
uspGetBillOfMaterials,2017-10-19 17:24:52.267 
uspGetEmployeeManagers,2017-10-19 17:24:52.273 
uspGetManagerEmployees,2017-10-19 17:24:52.280 
uspGetWhereUsedProductID,2017-10-19 17:24:52.283 
uspUpdateEmployeeHireInfo,2017-10-19 17:24:52.287 
uspUpdateEmployeeLogin,2017-10-19 17:24:52.290 
uspPrintError,2017-10-19 17:24:40.323 
uspUpdateEmployeePersonalInfo,2017-10-19 17:24:52.293 
uspLogError,2017-10-19 17:24:40.330 
uspSearchCandidateResumes,2017-10-19 17:24:52.297 
 
(10 行処理されました) 
1>

 

 

Excel に貼り付けると下図のような感じでスッキリと一覧を表示できます。

 

 

 

 

ストアドプロシージャのソースを出力する

ストアドプロシージャのソースを出力します。

exec sp_helptext の次の引数でストアドプロシージャを指定します。

1> exec sp_helptext sp_MScleanupmergepublisher 
2> go 
Text 
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- 
create procedure dbo.sp_MScleanupmergepublisher 
 
as 
 
    exec sys.sp_MScleanupmergepublisher_internal 
 
1> 

 

 

 

【例】

2> use adventureworks2016; 
3> go 
データベース コンテキストが 'AdventureWorks2016' に変更されました。 
1> exec sp_helptext 'adventureworks2016.dbo.usplogerror'; 
2> go 
Text 
---------------------------------------------------------------------------------------------------------------------------- 
 
 
-- uspLogError logs error information in the ErrorLog table about the 
 
-- error that caused execution to jump to the CATCH block of a 
 
-- TRY...CATCH construct. This should be executed from within the scope 
 
-- of a CATCH block otherwise it will return without inserting error 
 
-- information. 
 
CREATE PROCEDURE [dbo].[uspLogError] 
 
    @ErrorLogID [int] = 0 OUTPUT -- contains the ErrorLogID of the row inserted 
 
AS                               -- by uspLogError in the ErrorLog table 
 
BEGIN 
 
    SET NOCOUNT ON; 
 
 
 
    -- Output parameter value of 0 indicates that error 
 
    -- information was not logged 
 
    SET @ErrorLogID = 0; 
 
 
 
    BEGIN TRY 
 
        -- Return if there is no error information to log 
 
        IF ERROR_NUMBER() IS NULL 
 
            RETURN; 
 
 
 
        -- Return if inside an uncommittable transaction. 
 
        -- Data insertion/modification is not allowed when 
 
        -- a transaction is in an uncommittable state. 
 
        IF XACT_STATE() = -1 
 
        BEGIN 
 
            PRINT 'Cannot log error since the current transaction is in an uncommittable state. ' 
 
                + 'Rollback the transaction before executing uspLogError in order to successfully log error information.'; 
 
            RETURN; 
 
        END 
 
 
 
        INSERT [dbo].[ErrorLog] 
 
            ( 
 
            [UserName], 
 
            [ErrorNumber], 
 
            [ErrorSeverity], 
 
            [ErrorState], 
 
            [ErrorProcedure], 
 
            [ErrorLine], 
 
            [ErrorMessage] 
 
            ) 
 
        VALUES 
 
            ( 
 
            CONVERT(sysname, CURRENT_USER), 
 
            ERROR_NUMBER(), 
 
            ERROR_SEVERITY(), 
 
            ERROR_STATE(), 
 
            ERROR_PROCEDURE(), 
 
            ERROR_LINE(), 
 
            ERROR_MESSAGE() 
 
            ); 
 
 
 
        -- Pass back the ErrorLogID of the row inserted 
 
        SET @ErrorLogID = @@IDENTITY; 
 
    END TRY 
 
    BEGIN CATCH 
 
        PRINT 'An error occurred in stored procedure uspLogError: '; 
 
        EXECUTE [dbo].[uspPrintError]; 
 
        RETURN -1; 
 
    END CATCH 
 
END; 
 
1> 

 

 

Posted by 100%レンタルサーバーを使いこなすサイト管理人

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

AlphaOmega Captcha Medica  –  What Do You See?
     
 

このサイトはスパムを低減するために Akismet を使っています。コメントデータの処理方法の詳細はこちらをご覧ください

Secured By miniOrange