我有点陷入困境......我正在尝试从查询中获取输出并根据单个条件将其分解为多个文件。我收到一个错误,将varchar类型转换为int,我无法弄清楚原因。在SQL Server 2008中工作......
DECLARE @LOOP AS INT;
DECLARE @SQL AS VARCHAR(MAX);
DECLARE @BCP AS VARCHAR(MAX);
DECLARE @COUNTER AS INT;
DECLARE @FILENAME AS VARCHAR(MAX);
SET @COUNTER='1'
SELECT @LOOP = COUNT(DISTINCT LIST_ID) FROM DATA_TABLE
WHERE STATUS='2' AND LIST_ID IS NOT NULL ;
SET @SQL=(SELECT CUSTOMER_NO FROM CUSTOMER A, DATA_TABLE B
WHERE A.CUSTOMER_ID=B.CUSTOMER_ID AND A.STATUS='2' AND LIST_ID='+@LOOP+');
SET @FILENAME='QUERYOUT C:\Projects\FILE_"'+@LOOP+'.TXT'
WHILE @COUNTER<=@LOOP
BEGIN
SELECT
@BCP='BCP "'+@SQL+'+'+@FILENAME+''
SET @COUNTER=@COUNTER+1
END
GO
我得到的错误是:
Msg 245, Level 16, State 1, Line 10
Conversion failed when converting the varchar value '+@LOOP+' to data type int.
我正在尝试使用LOOP值让我知道每个文件的内容。例如,LOOP ='1'表示该文件包含与LIST_ID ='1'关联的客户记录
关于错误的想法?
答案 0 :(得分:0)
我不确定我到底知道你需要什么,但如果你想为每个LIST_ID
发出BCP命令,你需要循环它们并为每一个执行。
这可能不是你需要的,而是等到我下班回家后我会发布它。
DECLARE @FILENAME AS VARCHAR(MAX);
DECLARE @LISTID INT
DECLARE @LOOP AS INT;
DECLARE @BCP AS VARCHAR(MAX);
DECLARE @SQL AS VARCHAR(MAX);
DECLARE cur CURSOR FOR SELECT DISTINCT LIST_ID FROM DATA_TABLE WHERE STATUS='2' AND LIST_ID IS NOT NULL
OPEN cur
FETCH NEXT FROM cur INTO @LISTID
WHILE @@FETCH_STATUS = 0 BEGIN
SET @FILENAME='QUERYOUT C:\Projects\FILE_'+Cast(@LISTID AS Varchar)+'.TXT -c -t -T'
SET @SQL='(SELECT CUSTOMER_NO FROM CUSTOMER A, DATA_TABLE B WHERE A.CUSTOMER_ID=B.CUSTOMER_ID AND A.STATUS=''2'' AND LIST_ID='+@LISTID+')';
SELECT @BCP='BCP '+@SQL+' '+@FILENAME+''
EXEC xp_cmdshell @BCP
FETCH NEXT FROM cur INTO @LISTID
END
CLOSE cur
DEALLOCATE cur
答案 1 :(得分:0)
1.将varchar(max)更改为varchar(8000)
2.为所有表添加DBNAME.SCHEMA,因为默认情况下它将指向主数据库
在下方添加双引号(&#34;)
3. @FILENAME =&#39; QUERYOUT &#34; C:\ Projects \ FILE _&#39; + Cast(@LISTID AS Varchar)+&#39; .TXT &# 34; -c -t -T&#39;
4.&#39;(&#34; 的选择CUSTOMER_NO FROM CUSTOMER A,DATA_TABLE乙WHERE A.CUSTOMER_ID = B.CUSTOMER_ID AND A.STATUS =&#39;&#39; 2&#39 ;&#39; AND LIST_ID =&#39; + @ LISTID +&#39; &#34; )&#39;;