Results 1 to 4 of 4
  1. #1
    Join Date
    Feb 2003
    Posts
    41

    Question Unanswered: How can I write this SQL statement when the string value is a variable

    Hi. I was wondering how I might be able to write the following SQL statement | SET @AlertSymbol = N'MSFT' | when I want to replace the MSFT with the variable @StockSymbol?

    I'd like to do something like | SET @AlertSymbol = N'@StockSymbol' | but that doesn't seem to work as SQL isn't evaluating @StockSymbol but rather treating it as a string.

    All of the following return errors:

    SET @AlertSymbol = N@StockSymbol
    SET @AlertSymbol = N+@StockSymbol
    SET @AlertSymbol = N&@StockSymbol

    Thanks, Matt

  2. #2
    Join Date
    Mar 2002
    Location
    Bielefeld, Germany
    Posts
    69
    Just declare @StockSymbol as nchar or nvarchar and you can simply use

    SET @AlertSymbol = @StockSymbol

    The N in N'foo' tells SQL Server that 'foo' is in unicode. The same applies to all n<bar> datatypes.

  3. #3
    Join Date
    May 2002
    Posts
    299

    Re: How can I write this SQL statement when the string value is a variable

    Originally posted by mt404
    Hi. I was wondering how I might be able to write the following SQL statement | SET @AlertSymbol = N'MSFT' | when I want to replace the MSFT with the variable @StockSymbol?

    I'd like to do something like | SET @AlertSymbol = N'@StockSymbol' | but that doesn't seem to work as SQL isn't evaluating @StockSymbol but rather treating it as a string.

    All of the following return errors:

    SET @AlertSymbol = N@StockSymbol
    SET @AlertSymbol = N+@StockSymbol
    SET @AlertSymbol = N&@StockSymbol

    Thanks, Matt
    Nchar/varchar has higher precedence than char/varchar. Hence, an implicit conversion should take care of this for you.

    e.g.

    declare @AlertSymbol nvarchar(10),
    @StockSymbol varchar(10)

    set @StockSymbol='MSFT'

    set @AlertSymbol=@StockSymbol

    --sql2k
    select sql_variant_property(@AlertSymbol,'BaseType'), @AlertSymbol
    --
    -oj
    http://www.rac4sql.net

  4. #4
    Join Date
    Feb 2003
    Posts
    41

    Talking Thanks

    Thaks to both of you for helping me out and teaching me what the N'foo' actually meant.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •