sqlserver执行sql语句脚本

lishengyu 137 0
#!/bin/bash
user=sa
pass=lishengyu
host=192.168.2.152
db=test
port=1433
#修改默认换行符
old=$IFS
IFS='
'
#安装sqlcmd
check_install () {
which sqlcmd &> /dev/null
if [ $? -ne 0 ];then
    echo -e $bule"sqlcmd 没有安装....现在开始安装......"$end
    curl https://packages.microsoft.com/config/rhel/8/prod.repo > /etc/yum.repos.d/msprod.repo
    yum remove mssql-tools unixODBC-utf16-devel &> /dev/null
    echo -e $bule"请稍等......"$end
    sudo yum install mssql-tools unixODBC-devel -y
    echo -e $bule"添加环境变量......"$end
    echo 'export PATH="$PATH:/opt/mssql-tools/bin"' >> /etc/profile 
    source /etc/profile
    echo 'export PATH="$PATH:/opt/mssql-tools/bin"' >> /etc/bashrc 
    source /etc/bashrc
    which sqlcmd &> /dev/null
    if [ $? -eq 0 ];then
        echo -e $greed"sqlcmd 安装成功........"$end
    else
        echo -e $red"sqlcmd 安装失败,请检查........"$end
        exit
    fi
fi
}

#统计执行次数
k=1
#清空相关存放文件,初始化
> /tmp/do_sql.txt
> /tmp/done_sql.txt

echo "start........."
#开始循环
for line in `awk '{print $0}' sql.txt`
do
	#打印执行的序号
	echo "第 $k 条开始执行......"
	#输出读取到的内容到文件
	echo -e "$line" >> /tmp/do_sql.txt
	echo "go" >> /tmp/do_sql.txt
	#开始执行
		/opt/mssql-tools/bin/sqlcmd -U $user -P${pass} -S ${host},${port} -b -d ${db}  -i /tmp/do_sql.txt 
		[ $? -ne 0 ] &&  echo "check /tmp/do_sql.txt !!!!" && exit
	#初始化文件
		echo 
		echo -e "第 $k 条执行完成......"
		echo
		> /tmp/do_sql.txt
		> /tmp/do_sql.txt
	#记录已执行的语句
	echo "$line" >> /tmp/done_sql.txt
	let k++
done 
echo "done....."
echo "总共执行: $k"
IFS=$old

发表评论 取消回复
表情 图片 链接 代码

分享