SQL - 将char转换为精确长度varchar

时间:2010-06-24 13:03:40

标签: sql sql-server tsql

我正在尝试做这样的事情:

SELECT CAST(MYCHARCOL AS VARCHAR(LEN(MYCHARCOL))) 
FROM MYTABLE

如何将char列转换为varchar,这是char列中数据的确切长度?

2 个答案:

答案 0 :(得分:3)

你不能那样做

试试这个

SELECT CAST(RTRIM(MYCHARCOL) AS VARCHAR(8000)) FROM MYTABLE

答案 1 :(得分:2)

我的第一反应是为什么人们想要自己这样做?

我的第二反应是认为这很容易。结果设置长度不支持变量。虽然以下代码可能有效,但我建议您问问自己为什么要尝试此操作并从那里开始。

BEGIN/*Char X to Varchar X   ==========================================================================================================*/


  USE msdb

  SELECT
    t.name
   ,c.name
   ,typ.name
   ,c.max_length
  FROM
    sys.tables t
    JOIN sys.columns c
      ON t.object_id = c.object_id
    JOIN sys.types typ
      ON c.user_type_id = typ.user_type_id
  WHERE
    typ.name IN ( N'varchar', N'nvarchar', N'char', N'nchar' )


  DECLARE @max_len INTEGER ;
  SELECT
    @max_len = c.max_length
  FROM
    sys.tables t
    JOIN sys.columns c
      ON t.object_id = c.object_id
    JOIN sys.types typ
      ON c.user_type_id = typ.user_type_id
  WHERE
    typ.name IN ( N'varchar', N'nvarchar', N'char', N'nchar' )
    AND t.name = N'backupset'
    AND OBJECT_SCHEMA_NAME(t.object_id) = N'dbo'
    AND c.name = N'type'



  --attempt 1
  SELECT
    as_a_char = bs.type
   ,hardcoded = CAST(bs.type AS VARCHAR(1))
    --, code_specified = CAST ( bs.type AS VARCHAR ( @max_len ) ) --When uncommented, Msg 102, Level 15, State 1, Line 33 - Incorrect syntax near '@max_len'.
  FROM
    msdb.dbo.backupset bs


  --attempt 2
  DECLARE @SQL NVARCHAR(MAX)
  SET @SQL = N'
  --attempt 1
  SELECT 
    as_a_char = bs.type
    , hardcoded = CAST ( bs.type AS VARCHAR(1) )
    , code_specified = CAST ( bs.type AS VARCHAR ( {@max_len} ) ) 
  FROM msdb.dbo.backupset bs
'

  SET @sql = REPLACE(@SQL, '{@max_len}', @max_len) ;

  EXECUTE ( @sql )

END/*Char X to Varchar X     ==========================================================================================================*/