create table select

IT/DB 2025. 1. 7. 10:55
반응형

oracle

create table create_table_name as
select * from select_table_name

 

mssql

SELECT * INTO create_table_name FROM  (SELECT * FROM selcet_table_name)A

 

mysql

CREATE TABLE create_table_name AS
SELECT * FROM select_table_name
반응형
Posted by 투명강아지
,
반응형

이번에 다른 DB로 쿼리를 변환 해야 하는 일이 생겼다.

이 무식한 짓을 하려고 별의 별 구상을 다하던 중 툴이 있지 않을까 하고 검색해 보았다.

 

그래서 발견하게된 "sqlines" 진짜 잘 되려나 싶어 테스트를 해보았다.

온라인 에서 단순 쿼리만 변경 할 수도 있고 로컬에서 특정 쿼리만 또는 sql파일 자체를 변환 할 수 있었다.

 

온라인 방법
좌측에 입력 후 변환을 할 수 있다

 

 

오프라인 방법은 우선 해당 툴을 다운 받아준다.

다운로드

 

 

다운 후 압축을 풀면 3가지 버전이 나오게 된다.

 

1. 콘솔에서 특정 쿼리만 변경

 

 

2.프로그램으로 특정 쿼리 변환하기

 

 

 

3. 폴더에 들어있는 쿼리 변경하기

 

폴더의 경우 경로 설정을 \\\ 등으로 설정할 경우 하단의 모든 폴더의 쿼리를 찾아 변경하는것을 확인했다.

물론 변환 폴더에 동일한 경로로 폴더까지 자동 생성하였다.

반응형
Posted by 투명강아지
,
반응형

계정 생성 및 권한을 줄때 에러가 발생 된다.

 

보안개체의 사용자 생성 시 각 데이터 베이스의 사용자또한 함께 만들어 지기 때문인대

이대 스크립트를 보면

create "userid" for login "database" 를 하고 grant 작업이 진행이 되면서 각 DB에 사용자를 다시 만들기 때문이다

 

이때 발생 에러메세지로

제목: Microsoft SQL Server Management Studio "USERID"사용자 'DATABASE'에 대한 만들기이(가) 실패했습니다. (Microsoft.SqlServer.Smo)
추가 정보: Transact-SQL 문 또는 일괄 처리를 실행하는 동안 예외가 발생했습니다.(Microsoft.SqlServer.ConnectionInfo)
현재 데이터베이스에 사용자, 그룹 또는 역할 'GRANT'이(가) 이미 있습니다. (Microsoft SQL Server, 오류: 15023) 

 

각 DB의 사용자를 보게되면 사용자는 생성 되었지만 권한이 전부 빠져있을 것이다.

 

해결방법으로는 시스템으로 자동 보정을 해 주면 된다.

 

EXEC sp_change_users_login 'Auto_Fix', 'USERID'

 

위 명령어를 각 DB에 접속하여 보정해 준다.

반응형
Posted by 투명강아지
,
반응형

mssql 에서 활성 중인 또는 실행 대기 중인 쿼리와 세션을 확인 하여 lock에 걸린 문제의 세션을 kill 하기.

 

--세션
SELECT sqltext.TEXT, req.session_id, req.status, req.start_time, req.command, req.cpu_time, req.wait_time, req.total_elapsed_time, text_size
FROM sys.dm_exec_requests req
CROSS APPLY sys.dm_exec_sql_text(sql_handle) AS sqltext
order by sqltext.TEXT, req.status
;

-- lock
SELECT DISTINCT name AS database_name, session_id, host_name, login_time, login_name, reads, writes        
FROM    sys.dm_exec_sessions        
LEFT OUTER JOIN sys.dm_tran_locks ON sys.dm_exec_sessions.session_id = sys.dm_tran_locks.request_session_id        
INNER JOIN sys.databases ON sys.dm_tran_locks.resource_database_id = sys.databases.database_id
WHERE resource_type <> 'DATABASE'
AND request_mode LIKE '%X%'
--AND name ='YG1MES'
ORDER BY name 
;

--kill 은 서버에서
kill session_id
;

반응형
Posted by 투명강아지
,
반응형

컬럼에 identity 속성이 설정되어 있어서 임의적으로 데이터 삽입이 불가능.

 

insert into table_name

select * from table_name;

 

처리시 id값이 증가해야 함으로 컬럼명을 지정하지 않은 상태에서 데이터가 들어갈 수 없음.

 

SET IDENTITY_INSERT table_name ON

insert into table_name

select * from table_name

SET IDENTITY_INSERT table_name OFF

 

로 임시적으로 허용 후 데이터 처리 다시 테이블의 제약조건을 허용하여 처리가 가능함.

 

//** 2024.01.18 내용 추가 **//

위 건으로 처리 되지 않음.

SET IDENTITY_INSERT table_name ON

insert into table_name(column1, column2)

select column1, column2  from table_name

SET IDENTITY_INSERT table_name OFF

 

컬럼을 명시하여 처리해야 오류발생되지 않음.

 

아래는 mssql error내역에 대한 내용과 처리 관련한 내용을 표기함.

http://www.sql-server-helper.com/error-messages/msg-8101.aspx

 

SQL Server Helper - SQL Server Error Messages

Error Message Server: Msg 8101, Level 16, State 1, Line 2 An explicit value for the identity column in table "Table Name" can only be specified when a column list is used and IDENTITY_INSERT is ON. Causes This error happens when you are trying to insert a

www.sql-server-helper.com

 

SQL Server Error Messages - Msg 8101
Error Message
Causes
This error happens when you are trying to insert a new record into a table that contains an identity column without specifying the columns in the INSERT statement and you are assigning a value to the identity column instead of letting SQL Server assign the value.

To illustrate on how the error can be encountered:

CREATE TABLE [dbo].[Users] (
    [UserID]    INT NOT NULL IDENTITY(1, 1),
    [UserName]  VARCHAR(20) NOT NULL,
    [FirstName] VARCHAR(50) NOT NULL,
    [LastName]  VARCHAR(50) NOT NULL
)
GO

INSERT INTO [dbo].[Users] 
VALUES ( 1, 'superman', 'Clark', 'Kent' )
GO

Msg 8101, Level 16, State 1, Line 2
An explicit value for the identity column in table 'dbo.Users' can only be specified when a 
column list is used and IDENTITY_INSERT is ON.

If you specified the column names in the INSERT statement, you will get a different error message:

INSERT INTO [dbo].[Users] ( [UserID], [UserName], [FirstName], [LastName] )
VALUES ( 1, 'superman', 'Clark', 'Kent' )
GO

Msg 544, Level 16, State 1, Line 2
Cannot insert explicit value for identity column in table 'Users' when 
IDENTITY_INSERT is set to OFF.

Solution / Workaround:

There are two ways of avoiding any of the errors mentioned above.  The first option is not to include the identity column in the INSERT statement and let SQL Server assign the next identity value to the record:

INSERT INTO [dbo].[Users] ( [UserName], [FirstName], [LastName] )
VALUES ( 'superman', 'Clark', 'Kent' )
GO

The second option is to enable the IDENTITY_INSERT property for the table.  If you really want to specify the value for the identity column, this option is the one for you.

SET IDENTITY_INSERT [dbo].[Users] ON
GO

INSERT INTO [dbo].[Users] ( [UserID], [UserName], [FirstName], [LastName] )
VALUES ( 1, 'superman', 'Clark', 'Kent' )
GO

SET IDENTITY_INSERT [dbo].[Users] OFF
GO

Setting the IDENTITY_INSERT to ON for the table allows explicit values to be inserted into the identity column of a table.  At any given time, only one table in a session can have the IDENTITY_INSERT property set to ON.  If a table already has this property set to ON and a SET IDENTITY_INSERT ON statement is issued on another table, SQL Server will return the following error message:

Msg 8107, Level 16, State 1, Line 2
IDENTITY_INSERT is already ON for table 'dbo.Deparments'. 
Cannot perform SET operation for table 'dbo.Users'.

Execute permissions for the SET IDENTITY_INSERT default to the sysadmin fixed server role and the db_owner and db_ddladmin fixed database roles, and the object owner.

반응형
Posted by 투명강아지
,

SQLD 기출문제(CBT)

IT/DB 2023. 3. 2. 15:54
반응형

SQLD 기출문제 CBT형태로 테스트를 할수 있는 사이트

 

https://quizeey.com/sqlp-developer

반응형
Posted by 투명강아지
,

MariaDB 시간 설정

IT/DB 2019. 7. 29. 11:54
반응형

mariadb를 그냥 설치시 서버환경에 따라 시간이 맞지 않는 경우가 있다.

 

이때 한국시간으로 설정을 해주어야 한다.

SELECT @@global.time_zone, @@session.time_zone;

글로벌 타임존과 세션 타임존이

SYSTEM으로 표기된다면 설정이 되어 있지 않은 기본값이라는 것이다.

 

DB서버를 정지 후 설정한다.

설정 완료 후 재시작 해도 된다.

sudo systemctl stop mariadb
sudo vi /etc/my.cnf.d/server.cnf
...더보기

[mysqld]

default-time-zone='+9:00'

mysqld아래에 입력해 준다.

한국은 UTC기준으로 GMP+9임으로 위와 같이 설정

 

sudo systemctl start mariadb
SELECT @@global.time_zone, @@session.time_zone;

 

확인 후 설정 완료!

반응형
Posted by 투명강아지
,
반응형

MariaDB의 데이터가 쌓이는 실제 디스크의 위치를 변경하여 사용하고자 할때 적용한다.

용향이 큰 서버일경우나 또는 데이터가 쌓이는 곳을 다른 파티션 또는 디스크로 관리하기 위함.

 

CentOS7 & MariaDB 10.4 기준입니다.

 

mysql -u root -p

root 로 접속 하여 현재 데이터디렉토리를 확인 합니다.

MariaDB [(none)]> select @@datadir;

 

기본적으로 설치했을 경우 /var/lib/mysql에 데이터디렉토리가 설정되어 있습니다.

 

자 이제 변경해 봅시다.

 

1. 서비스 중지

sudo systemctl stop mariadb

 

2. 새로운 디렉토리 생성 및 설정

 - 저의 경우 파티션을 나누었기 때문에 /database로 변경만 하도록 하겠습니다.

 

설정내용 연결

sudo rsync -av /var/lib/mysql /database

sudo chown -R mysql:mysql /database

 

3. data디렉토리 변경

sudo vi /etc/my.cnf
...더보기

[mysqld]

datadir=/home/data/mysql

socket=/home/data/mysql/mysql.sock

 

[client]

socket=/home/data/mysql/mysql.sock

#symbolic-links=0

#sql_mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES

 

4. SELinux 보안 context 추가 및 서비스 시작

sudo semanage fcontext -a -t mysqld_db_t "/database/mysql(/.*)?"
sudo restorecon -R /database/mysql

sudo systemctl start mariadb

 

5. 확인

mysql -u root -p

root 로 접속 하여 데이터디렉토리가 변경된 것을 확인 합니다.

MariaDB [(none)]> select @@datadir;

6. 기존 디렉토리 삭제

sudo rm -rf /var/lib/mysql

df -h

마지막으로 용량 확보 확인 후 끝.

 

완료!

반응형

'IT > DB' 카테고리의 다른 글

SQLD 기출문제(CBT)  (0) 2023.03.02
MariaDB 시간 설정  (0) 2019.07.29
CentOS7 & MariaDB 설치  (0) 2019.07.22
maria DB index 생성  (0) 2019.07.13
mariaDB 계정 생성 및 database 접근권한 설정  (0) 2019.07.10
Posted by 투명강아지
,

CentOS7 & MariaDB 설치

IT/DB 2019. 7. 22. 15:08
반응형

MariaDB 설치

 

1. repository 설정 파일 생성

sudo vi /etc/yum.repos.d/mariadb.repo

 

 - MariaDB 10.1 Ver.

mariadb.repo에 입력

[mariadb]
name = MariaDB
baseurl = http://yum.mariadb.org/10.1/centos7-amd64
gpgkey=https://yum.mariadb.org/RPM-GPG-KEY-MariaDB
gpgcheck=1

 

2. MariaDB Install

sudo yum install MariaDB-server

 

3. MariaDB 초기 설정

sudo systemctl start mariadb

sudo mysql_secure_installation

Enter current password for root? enter

Switch to unix_socket authentication? enter

Change the root password? y

 - root 비밀번호 입력

Remove anonymous users? y

 - 테스트용 계정 삭제

Disallow root login remotely? y

 - root 외부 접속 허용? (개발단계라 오픈, 프로젝트 오픈시 제한)

Remove test database and access to it? y

 - 테스트용 데이터 베이스 삭제

Reload privilege tables now? y

 - 설정을 바로 적용

 

 - Thanks for using MariaDB!

초기 설정 완료!

 

4. 부팅시 DB자동 실행 설정

sudo systemctl enable mariadb

 

5. MariaDB 세부 설정

 - UTF-8 설정

sudo vi /etc/my.cnf.d/server.cnf

 

[mysqld] 아래에 아래 항목 추가

character-set-server=utf8mb4
collation-server=utf8mb4_bin

 

 - Auto Commit 설정

MariaDB는 기본적으로 AutoCommit이 True임으로 Fasle로 설정을 변경해 준다

 

[mysqld] 아래에 아래 항목 추가

autocommit=0

 

 

최종 설정 적용

sudo systemctl restart mariadb
반응형

'IT > DB' 카테고리의 다른 글

MariaDB 시간 설정  (0) 2019.07.29
CentOS7 & MariaDB 데이터 베이스 저장공간 변경  (0) 2019.07.25
maria DB index 생성  (0) 2019.07.13
mariaDB 계정 생성 및 database 접근권한 설정  (0) 2019.07.10
ms-sql backup & restore  (0) 2019.07.08
Posted by 투명강아지
,

maria DB index 생성

IT/DB 2019. 7. 13. 14:34
반응형

 - 인덱스 확인

show index from table_name;

 

 - 인덱스 생성

create index index_name on table_name (column_name);

 

 - 인덱스 삭제

drop index index_name on table_name;

 

 - 복합 인덱스 생성

create index index_name on table_name (column_name1, column_name2);

 

 - 인덱스 중지

alter table table_name DISABLE index_name;

 

* 인덱스 중지상태일 경우 show index로 확인시 해당 index의 comment에 disble로 표기됨

 

반응형

'IT > DB' 카테고리의 다른 글

CentOS7 & MariaDB 데이터 베이스 저장공간 변경  (0) 2019.07.25
CentOS7 & MariaDB 설치  (0) 2019.07.22
mariaDB 계정 생성 및 database 접근권한 설정  (0) 2019.07.10
ms-sql backup & restore  (0) 2019.07.08
MDB 비밀번호 찾기, VIEWER  (0) 2019.04.24
Posted by 투명강아지
,