Sql Case、Replicate 和 Trim 函数的查询问题

Sql Query problems with Case, Replicate and Trim functions

我的 SQL 查询有一些问题。 table 名称是 debitorders,它由以下列组成:

  1. 名字(varchar(50),null)
  2. 姓氏(varchar(50),null)
  3. 帐号(varchar(50),null)
  4. 账户类型(varchar(50),null)
  5. 银行名称(varchar(50),null)
  6. 分支(varchar(50),null)
  7. 金额(varchar(50),null)
  8. 日期(日期,空)

到目前为止,这是我们的查询:

SET @BankName = 'ABSA'
--SET @BankName = 'First National Bank'
SET @QueryResultA = (SELECT CASE @BankName 
                     WHEN 'ABSA' THEN 'ABSA            0040000146162'
                     WHEN 'First National Bank' THEN 'First National B0020000045603'
                     END)
--PRINT @QueryResultA
SET @Amount = (SELECT amount FROM debitorders)
SELECT
       left(LTRIM(RTRIM(firstname)),1) + '' + CONVERT (varchar(15),LTRIM(RTRIM(surname)),1),
       (SELECT left(cast(LTRIM(RTRIM(accountnumber)) as varchar(14))+replicate(' ',14),14) ),
       CASE accounttype 
         WHEN 'cheque' 
            THEN left(cast('CH' as varchar(3))+replicate(' ',3),3) 
         WHEN 'savings' 
            THEN left(cast('SAV' as varchar(3))+replicate(' ',3),3)
         WHEN 'credit card' 
            THEN left(cast('CC' as varchar(3))+replicate(' ',3),3)
         WHEN 'other' 
            THEN left(cast('OTH' as varchar(3))+replicate(' ',3),3)
      END, 
      left(cast(LTRIM(RTRIM(branch)) as varchar(10))+replicate(' ',10),10),   
      REPLICATE('0', 7 - DATALENGTH (REPLACE(amount,'.',''))) + LTRIM(RTRIM(REPLACE(amount,'.',''))),
      REPLACE(CONVERT(VARCHAR, date,103),'/','') AS DebitDate
      --REPLACE(CONVERT(VARCHAR(10), date, 104) AS [DD.YYYY.MM]),'.',''
FROM debitorders
WHERE bankname = @BankName

结果应该是:

  1. 名字(垫面:n/a,Length:1)
  2. 姓氏(垫side:right,Length:15)
  3. 帐号(填充 side:right、Length:14)
  4. 账户类型(垫side:right,Length:3)
  5. 分支(垫side:right,Length:10)
  6. 金额(垫side:left,Length:7)
  7. 日期(垫面:n/a,Length:8,设置格式为ddyyyymm)

为什么无法识别这些列?

您需要声明您的变量:

DECLARE @BankName VARCHAR(50) = 'ABSA';

您还试图在@Amount 变量中设置多条记录。你需要在这里聚合吗?

您运行您的查询是否针对正确的数据库?您的借方订单 table 是在哪里创建的?

我会说首先检查你是否运行你对主数据库的查询。

这个 link 有更多信息:http://blog.sqlauthority.com/2012/08/31/sql-server-error-fix-msg-208-invalid-object-name-dbo-backupset-invalid-object-name-dbo-backupfile/