1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

MSSQLに関わる小ネタ(昔のメモ)

Posted at

MSSQLに関わる小ネタ

SQLServerで文字列のバイト長を取得するクエリ
1.バイト数を取得
DATALENGTH(CONVERT(VARCHAR(30), [COLUMN]))

2.左から2バイト取得(LEFT()関数もどき)
CONVERT(VARCHAR(2), [COLUMN])

3.最後から4バイト取得(RIGHT()関数もどき)
REVERSE(CONVERT(VARCHAR(4), REVERSE([COLUMN])))


Padleft,Padrightもどき
(''00000'')はカラムの最大桁まで指定しておく。
5桁、左、0埋め
SELECT RIGHT(''00000'' + COL ,5) AS CODE FROM TABLE

5桁、右、0埋め
SELECT LEFT(COL + ''00000'' ,5) AS CODE FROM TABLE


重複行の取得
SQLServerはこれでいけた。

SELECT [COLUMN(S)]
FROM [TABLE]
GROUP BY [COLUMN(S)]
HAVING COUNT > 1

SQLServerでリンクサーバの構成・解除
2008までかな?

--リンクサーバ構成
USE master
GO

EXEC master.dbo.sp_addlinkedserver
@server = N''[ServerAddress]\\[INSTANCE]'' ,
@srvproduct = N''SQL Server'';
GO

EXEC master.dbo.sp_addlinkedsrvlogin
@rmtsrvname = N''[ServerAddress]\\[INSTANCE]'' ,
@useself = N''False'', 
@locallogin = NULL , 
@rmtuser = ''[USER_ID]'', 
@rmtpassword = ''[PASSWD]'';
GO
--リンクサーバ削除
USE master
GO

EXEC master.dbo.sp_dropserver 
@server = N''[ServerAddress]\\[INSTANCE]'' ,
@droplogins = ''droplogins'';
GO
--リンクサーバ取得
select * from sys.servers where is_linked = ''1''
and name = ''''
--確認用クエリ
SELECT name FROM [ServerAddress]\\[INSTANCE].MASTER.SYS.DATABASES

SSMSで実行結果をミリ秒まで出す

DECLARE @StartTime datetime -- 処理開始時刻保存用変数
SET @StartTime = GETDATE() -- 処理開始時刻設定

/* ↓↓↓ 以下に処理時間を計測したいSQL文を書く*/

/* ↑↑↑ ここまで計測対象 */
SELECT CONVERT(varchar,GETDATE()-@StartTime,114) AS 実行時間 

SQLの実行時間をミリ秒単位で計測する方法


全テーブルの件数を取得

SELECT A.NAME, B.ROW_COUNT 
FROM SYS.TABLES A
LEFT JOIN SYS.DM_DB_PARTITION_STATS B
ON A.OBJECT_ID = B.OBJECT_ID
ORDER BY A.OBJECT_ID
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?