Case,Replicate和Trim函数的Sql Query问题

时间:2015-03-24 12:29:36

标签: sql-server tsql case trim replicate

我的SQL查询中存在一些问题。表名为 debitorders ,其中包含以下列:

  1. firstname (varchar(50),null)
  2. 姓氏(varchar(50),null)
  3. accountnumber (varchar(50),null
  4. accounttype (varchar(50),null)
  5. bankname (varchar(50),null)
  6. branch (varchar(50),null)
  7. 金额(varchar(50),null)
  8. 日期(日期,空)
  9. 这是我们目前的查询:

    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. 名字(垫侧:不适用,长度:1)
    2. 姓(垫侧:右,长度:15)
    3. accountnumber(垫侧:右,长度:14)
    4. accounttype(pad side:right,Length:3)
    5. 分支(垫侧:右,长度:10)
    6. 金额(垫侧:左,长度:7)
    7. 日期(垫侧:不适用,长度:8,设置格式为ddyyyymm)
    8. 为什么不识别列?

2 个答案:

答案 0 :(得分:0)

您需要声明变量:

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

您还尝试在@Amount变量中设置多个记录。你需要聚合吗?

答案 1 :(得分:0)

您是否针对正确的数据库运行查询?你的债务人表在哪里创建了?

我想首先检查一下你是不是在对master数据库运行查询。

此链接提供了更多信息:http://blog.sqlauthority.com/2012/08/31/sql-server-error-fix-msg-208-invalid-object-name-dbo-backupset-invalid-object-name-dbo-backupfile/