WHERE clause on SQL Server “Text” data type

前端 未结 7 2456
不思量自难忘°
不思量自难忘° 2020-11-28 09:52

Where [CastleType] is set as data type \"text\" in SQL Server and the query is:

SELECT *
FROM   [Village]
WHERE  [CastleType] = \'foo\' 

I

相关标签:
7条回答
  • 2020-11-28 10:00

    If you can't change the datatype on the table itself to use varchar(max), then change your query to this:

    SELECT *
    FROM   [Village]
    WHERE  CONVERT(VARCHAR(MAX), [CastleType]) = 'foo'
    
    0 讨论(0)
  • 2020-11-28 10:01

    That is not what the error message says. It says that you cannot use the = operator. Try for instance LIKE 'foo'.

    0 讨论(0)
  • 2020-11-28 10:03

    Please try this

    SELECT *
    FROM   [Village]
    WHERE  CONVERT(VARCHAR, CastleType) = 'foo'
    
    0 讨论(0)
  • 2020-11-28 10:14

    This works in MSSQL and MySQL:

    SELECT *
    FROM   Village
    WHERE  CastleType LIKE '%foo%'; 
    
    0 讨论(0)
  • 2020-11-28 10:16

    Another option would be:

    SELECT * FROM [Village] WHERE PATINDEX('foo', [CastleType]) <> 0
    
    0 讨论(0)
  • 2020-11-28 10:22

    You can use LIKE instead of =. Without any wildcards this will have the same effect.

    DECLARE @Village TABLE
            (CastleType TEXT)
    
    INSERT INTO @Village
    VALUES
      (
        'foo'
      )
    
    SELECT *
    FROM   @Village
    WHERE  [CastleType] LIKE 'foo' 
    

    text is deprecated. Changing to varchar(max) will be easier to work with.

    Also how large is the data likely to be? If you are going to be doing equality comparisons you will ideally want to index this column. This isn't possible if you declare the column as anything wider than 900 bytes though you can add a computed checksum or hash column that can be used to speed this type of query up.

    0 讨论(0)
提交回复
热议问题