0

我有点卡住了...我试图从查询中获取输出并根据单个条件将其分解为多个文件。我收到将 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' 关联的客户记录

对错误的想法?

4

2 回答 2

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
于 2014-10-31T16:02:50.343 回答
0

1.将 varchar(max) 更改为 varchar(8000)
2.为所有表添加 DBNAME.SCHEMA,因为默认情况下它将指向主数据库。

3. @FILENAME='QUERYOUT " C:\Projects\FILE_'+Cast(@LISTID AS Varchar)+'.TXT " -c -t -T'
4. '( " SELECT CUSTOMER_NO FROM客户 A,DATA_TABLE B 其中 A.CUSTOMER_ID=B.CUSTOMER_ID AND A.STATUS=''2'' AND LIST_ID='+@LISTID+' " )';

于 2015-07-17T14:26:43.607 回答