我在 docker 镜像中运行 sql 脚本时遇到问题。 我正在构建一个 dockerfile,如下所示:
FROM mcr.microsoft.com/mssql/server:2019-latest
USER root
RUN mkdir -p /app/config
WORKDIR /app/config
# Copy all the scripts to create tables, views, etc...
COPY sample_data/ /app/config
EXPOSE 1433
ENV ACCEPT_EULA=Y \
MSSQL_SA_PASSWORD=SuperDup3Rsecre7 \
MSSQL_PID=Express
RUN chmod +x /app/config/entrypoint.sh
RUN chmod +x /app/config/create_db.sh
ENTRYPOINT ["./entrypoint.sh"]
这是我的
entrypoint.sh
和create_db.sh
# entrypoint.sh
#!/bin/bash
# Start the script to create the DB
/app/config/create_db.sh &
# Start SQL Server
/opt/mssql/bin/sqlservr
# create_db.sh
DBSTATUS=1
ERRCODE=1
i=0
while [[ $DBSTATUS -ne 0 ]] && [[ $i -lt 60 ]] && [[ $ERRCODE -ne 0 ]]; do
i=$i+1
DBSTATUS=$(/opt/mssql-tools/bin/sqlcmd -h -1 -t 1 -U sa -P $MSSQL_SA_PASSWORD -Q "SET NOCOUNT ON; Select SUM(state) from sys.databases")
ERRCODE=$?
sleep 1
done
if [[ $DBSTATUS -ne 0 || $ERRCODE -ne 0 ]]; then
echo "SQL Server took more than 60 seconds to start up or one or more databases are not in an ONLINE state"
exit 1
fi
# Run the setup script to create the DB and the schema in the DB
/opt/mssql-tools/bin/sqlcmd -S localhost -U sa -P $MSSQL_SA_PASSWORD -d master -i "ddl_001_tables.sql"
/opt/mssql-tools/bin/sqlcmd -S localhost -U sa -P $MSSQL_SA_PASSWORD -d master -i "ddl_002_views.sql"
创建所有表的第一个脚本工作正常,但第二个脚本带有视图(只是一个简单的视图来突出问题)
-- ddl_002_views.sql
create view new_view1 as
select TOP 1 name from sys.tables;
create view new_view2 as
select TOP 1 name from sys.tables;
失败的原因是:
Msg 156, Level 15, State 1, Server 6f49cec5c8ab, Procedure new_view1, Line 4
Incorrect syntax near the keyword 'create'.
当我通过 IDE(在我的例子中是 DBeaver)执行脚本
ddl_002_views.sql
时,它工作得很好。
有人知道我做错了什么或者我错过了什么吗? 预先感谢。
它与 docker 无关,您不能尾随
create
语句。您需要在它们之间添加 GO;
。
create view new_view1 as
select TOP 1 name from sys.tables;
GO
create view new_view2 as
select TOP 1 name from sys.tables;
由于评论,我认为您需要将它们移至不同的文件中。
好吧 - 我想我明白了:) 我必须在没有
GO
的 ;
语句之间添加,例如:
create view new_view1 as
select TOP 1 name from sys.tables;
GO
create view new_view2 as
select TOP 1 name from sys.tables;
谢谢