DECLARE @csvFileName varchar(50)
DECLARE @SelectOut varchar(8000)
SET @csvFileName = 'D:\csv Files\' + CAST(year(SYSDATETIME()) AS VARCHAR) + CAST(month(SYSDATETIME()) AS VARCHAR) +
CAST(day(SYSDATETIME()) AS VARCHAR) + 'IninUsers.csv'
SET @SelectOut = 'BCP "SELECT DISTINCT u.firstName,u.lastName,wc.name,tw.dateTimeFrom,tw.dateTimeTo
FROM TA_WhcAssigned tw
INNER JOIN TA_Whc wc
ON tw.whcid=wc.id
INNER JOIN users u
ON u.pin = tw.pin
INNER JOIN DepartmentsAdmin da
ON da.pin = u.pin
INNER JOIN Departments d
ON da.departmentId = d.parent
WHERE (year(tw.dateTimeFrom)=2019 or year(tw.dateTimeFrom) = 2018)
ORDER BY dateTimeFrom DESC " queryout ' + @csvFileName + ' -c -T'
EXEC xp_cmdshell @SelectOut
我所能获得的就是如何使用bcp语法:
答案 0 :(得分:0)
我解决了我的问题。一行BCP,还有一些用于 获取列。
如果有人感兴趣,这里是完整的代码:
DECLARE @csvFileName varchar(50) 宣告@SelectOut varchar(8000) 十进制@sql varchar(8000) 宣告@sqlLine varchar(8000)
SET @ sql ='SELECT DISTINCT cast(u.pin如varchar(50))pin,cast(u.firstName如varchar(50))firstname,
强制转换(u.lastName为varchar(50))姓氏,cast(wc.name为varchar(50))名称,
replace(convert(varchar(50),tw.dateTimeFrom,103),''/'',''。'')+''''+
convert(nvarchar,tw.dateTimeFrom,8)dateTimeFrom,replace(convert(varchar(50),tw.dateTimeTo,103),''/'',''。'')+''''+
convert(nvarchar,tw.dateTimeTo,8)dateTimeTo
从TA_WhcAssigned tw
INNER JOIN TA_Whc wc
在tw.whcid = wc.id上
INNER JOIN用户u
开启u.pin = tw.pin
INNER JOIN DepartmentsAdmin da
开启da.pin = u.pin
内联部门d
开启da.departmentId = d.parent
在哪里(year(tw.dateTimeFromFrom)= 2019或year(tw.dateTimeFrom)= 2018)“'
SET @sqlLine = REPLACE(REPLACE(@ sql,CHAR(13),''),CHAR(10),'')
SET @csvFileName ='“ D:\ csv Files \'+ CAST(year(SYSDATETIME())AS VARCHAR)+ CAST(month(SYSDATETIME())AS VARCHAR)+ CAST(day(SYSDATETIME())AS VARCHAR)+'IninUsers.csv“'
SET @SelectOut ='BCP“选择``Pin'',``First Name'',``Last Name'',``Name'',``Date From'',``Date To''合并所有'+ @sqlLine +'queryout'+ @csvFileName +'-c -t,-T -S“'+ @@服务器名+'” -d“ BoneIDa2”'
EXEC xp_cmdshell @SelectOut
唯一的问题是创建逗号分隔的值csv -因此它是UTF-8,而不是MS-DOS。因为我的特殊字符显示错了。