我是SQL Server的新手。我正在使用SQL Server 2008.我有一个名为proc_generate_excel_with_columns
的过程。该过程将数据库名称,表名称和Excel文件路径作为输入参数。
该过程从指定的SQL Server表中选取数据,并将其放入虚拟文件中,最后将虚拟文件的内容复制到指定的Excel文件中。
当我运行该程序时,我收到以下错误。
SQLState = 08001 NativeError = 2
错误= [Microsoft] [SQL Server Native Client 10.0]建立与SQL Server的连接时发生网络相关或实例特定错误。找不到服务器或无法访问服务器。检查实例名称是否正确,SQL服务器是否配置为允许远程连接。
程序代码如下。
create procedure [dbo].[proc_generate_excel_with_columns]
(
@db_name varchar(100),
@table_name varchar(100),
@file_name varchar(100)
)
as
--Generate column names as a recordset
declare @columns varchar(8000), @sql varchar(8000), @data_file varchar(100)
select
@columns = coalesce(@columns + ',', '') + column_name + ' as ' + column_name
from
information_schema.columns
where
table_name = @table_name
select
@columns = '''''' + replace(replace(@columns, ' as ', ''''' as '), ',',',''''')
--Create a dummy file to have actual data
select
@data_file = substring(@file_name, 1, len(@file_name) - charindex('\', reverse(@file_name))) + '\data_file.xls'
--Generate column names in the passed EXCEL file
set @sql='exec master..xp_cmdshell ''bcp " select * from (select '+@columns+') as t" queryout "'+@file_name+'" -S "SBHATT6440" -c -T'''
exec(@sql)
--Generate data in the dummy file
set @sql='exec master..xp_cmdshell ''bcp "select * from '+@db_name+'..'+@table_name+'" queryout "'+@data_file+'" -S "SBHATT6440" -c -T'''
exec(@sql)
--Copy dummy file to passed EXCEL file
set @sql= 'exec master..xp_cmdshell ''type '+@data_file+' >> "'+@file_name+'"'''
exec(@sql)
--Delete dummy file
set @sql= 'exec master..xp_cmdshell ''del '+@data_file+''''
This is the image of SQL Server Services
This is the image of Protocols for SQLEXPRESS
非常感谢任何帮助。如果需要,我可以提供任何额外的信息。