TSQL varchar string manipulation

后端 未结 5 1178
失恋的感觉
失恋的感觉 2021-01-14 22:36

I have a variable which contains the following string: AL,CA,TN,VA,NY

I have no control over what I get in that variable (comes from reporting services)

I

相关标签:
5条回答
  • 2021-01-14 23:03
    declare @x varchar(50) = 'AL,CA,TN,VA,NY'
    
    select '''' + REPLACE(@x, ',', ''',''') + ''''
    
    0 讨论(0)
  • 2021-01-14 23:15

    For a more generic answer, when you don't know what your output will look like exactly, use regular expressions.

    This would let you you match on something like [A-Z]{2} and replace it with '$&'.

    A commenter suggested this is overkill for this task - agreed, if you can guarantee you will always get a string like that. However, other people find these question pages later with similar, but not exact, problems, so other options are helpful to have.

    0 讨论(0)
  • 2021-01-14 23:17

    Don't bother with dynamic sql.

    You need to convert the string to a table so A,B,C,D

    becomes

    Value A B C D

    using a function like http://www.sqlusa.com/bestpractices/training/scripts/splitcommadelimited/

    then you can use CROSS APPLY (which is like joining to a table, but a table created by a function) or you can just put it in a table variable and join to that

    0 讨论(0)
  • 2021-01-14 23:18

    I want to know y does the following script run in SQL and not in T-SQL


    DECLARE @tblName varchar(30) SET @tblName = CONVERT(VARCHAR(20),GETDATE(),112) + 'Table'

    DECLARE @sql nvarchar(4000) SELECT @sql = 'CREATE TABLE "' + @tblName + '" ( ID VARCHAR(15), Name VARCHAR(15) )'

    EXEC(@sql)

    go

    it gives you the error

    Msg 170, Sev 15: Line 1: Incorrect syntax near '20090714Table'. [SQLSTATE 42000]

    0 讨论(0)
  • 2021-01-14 23:21

    I ended up doing something very similar that I thought I'd post. (I'll give credit to Mitch however)

    This takes care of the middle:

    SET @StateList = REPLACE(@StateList, ',', ''',''')

    Then quote the edges:

    SET @WhereClause1 = @WhereClause1 + 'AND customerState IN (''' + @StateList + ''') '

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