Sql server 将一个表的内容的脚本生成为.sql文件(通过代码)

Sql server 将一个表的内容的脚本生成为.sql文件(通过代码),sql-server,tsql,Sql Server,Tsql,我是否可以创建一个存储过程,将已定义表的内容生成到作为其(存储过程)参数传递的路径 如果您指的是表结构,那么下面是让您开始使用的SQL select column_name,data_type,is_nullable from information_schema.columns where table_name = '<table name>' order by ordinal_position 请尝试下面的代码 create procedure dbo.ShowAllRows

我是否可以创建一个存储过程,将已定义表的内容生成到作为其(存储过程)参数传递的路径

如果您指的是表结构,那么下面是让您开始使用的SQL

select column_name,data_type,is_nullable
from information_schema.columns
where table_name = '<table name>'
order by ordinal_position
请尝试下面的代码

create procedure dbo.ShowAllRows (@tabName VARCHAR(200) )
as
begin
    declare @Sql    NVARCHAR(2000)
    set @Sql = 'select * FROM '+@tabName
    EXEC (@sql)
end
go
exec ShowAllRows  'sys.configurations'
我错过了路径部分,我假设您想要上面类型的代码,还有第二个参数,即@outputFileName

如果您的SQL server有权访问文件路径,并且您可以运行XP\u CMDShell,则可以执行以下操作

create procedure dbo.ShowAllRows (@tabName VARCHAR(200),@outPath VARCHAR(200) )
as
begin
    declare @Sql    NVARCHAR(2000)

    set @sql = 'bcp '+@tabName+' out '+@outPath+' -U<user> -P<password> '
    print @sql
    EXEC xp_cmdShell @sql
end
创建过程dbo.ShowAllRows(@tabName VARCHAR(200),@outPath VARCHAR(200))
作为
开始
声明@Sql NVARCHAR(2000年)
set@sql='bcp'+@tabName+'out'+@outPath+'-U-P'
打印@sql
EXEC xp_cmdShell@sql
结束
如果您不想在过程中输入用户名和密码,也可以使用-T进行可信连接

尝试以下操作:

create proc spOutputData @tbl varchar(500)
as

declare @cmd varchar(4000)

SELECT @cmd = 'bcp ' + @tbl + ' out c:\OutFile.txt -c  -q -Shpas -T'

exec xp_cmdshell @cmd
测试:


您可以在Management Studio中查询表,右键单击结果并选择“另存为”保存到csv文件。他需要存储过程从代码等中执行此操作。按内容,您可以显示所有行还是表结构?这两个都可以使用动态SQL轻松实现…我希望从存储过程运行t!SQL Server阻止访问组件“xp\u cmdshell”的过程“sys.xp\u cmdshell”,因为此组件作为此服务器安全配置的一部分已关闭。系统管理员可以通过使用sp\u configure启用“xp\u cmdshell”。有关启用“xp_cmdshell”的更多信息,请参见。我将在共享主机上运行此操作!
create proc spOutputData @tbl varchar(500)
as

declare @cmd varchar(4000)

SELECT @cmd = 'bcp ' + @tbl + ' out c:\OutFile.txt -c  -q -Shpas -T'

exec xp_cmdshell @cmd
spOutputData 'master.dbo.syslogins'