DB2

Posted by zhangyingji on August 22, 2019

前言

DB2与MySQL语法比较相似

基本操作

连接数据库

# 连接到schema
db2 connect to <schemaName>

# 切换schema
db2 set current schema <schemaName>

查看表结构

describe table <tableName>

insert into table_name(column_name, ...) 
    values(theValue, ...)

delete from table_name where column_name = theValue

select column_name from table_name
    where column_name = theValue

union重复记录不显示

update table_name
    set column_name = newValue
        ...

常用函数

CHAR()INR()

强制类型转换 CAST (expression AS data_type)

CAST(theValue AS char(10))

截取字符串 substr(字符串,截取开始位置,截取长度)

脚本

执行sql脚本

db2 -td@ -vf <sqlFileName>

新增字段

BEGIN
IF NOT EXISTS (
    SELECT colname FROM SYSCAT.COLUMNS
        WHERE TABNAME = '' AND COLNAME = '' AND TABSCHEMA = ''
    )
THEN
    EXECUTE IMMEDIATE
        'ALTER <TABLE tableName> ADD <columnName> VARCHAR(10)'