When to use SET vs SELECT when assigning values to variables in SQL Server

By: Atif Shehzad   |   Comments (13)   |   Related: > TSQL

SET and SELECT may be used to assign values to variables through T-SQL. Both fulfill the task, but in some scenarios unexpected results may be produced. In this tip I elaborate on the considerations for choosing between the SET and SELECT methods for assigning a value to variable.

In most cases SET and SELECT may be used alternatively without any effect.

Following are some scenarios when consideration is required in choosing between SET or SELECT. Scripts using the AdventureWorks database are provided for further clarification.

Part 1 and 2 are mentioned in the scripts below. It would be better if you run each part of the script separately so you can see the results for each method.

Returning values through a query

Whenever you are assigning a query returned value to a variable, SET will accept and assign a scalar (single) value from a query. While SELECT could accept multiple returned values. But after accepting multiple values through a SELECT command you have no way to track which value is present in the variable. The last value returned in the list will populate the variable. Because of this situation it may lead to un-expected results as there would be no error or warning generated if multiple values were returned when using SELECT. So, if multiple values could be expected use the SET option with proper implementation of error handling mechanisms.

To further clarify the concept please run script # 1 in two separate parts to see the results

Part 1 of the script should be successful. The variable is populated with a single value through SET. But in part 2 of the script the following error message will be produced and the SET statement will fail to populate the variable when more than one value is returned.

Error message generated for SET

Hence SET prevented assignment of an ambiguous value.

In case of SELECT, even if multiple values are returned by the query, no error will be generated and there will be no way to track that multiple values were returned and which value is present in the variable. This is demonstrated in the following script.

Both part 1 and 2 were executed successfully. In part 2, multiple values have been assigned and accepted, without knowing which value would actually populate the variable. So when retrieval of multiple values is expected then consider the behavioral differences between SET and SELECT and implement proper error handling for these circumstances.

Assigning multiple values to multiple variables

If you have to populate multiple variables, instead of using separate SET statements each time consider using SELECT for populating all variables in a single statement. This can be used for populating variables directly or by selecting values from database.

Consider the following script comparing the use of SELECT and SET.

If you are using SET then each variable would have to be assigned values individually through multiple statements as shown below.

Obviously SELECT is more efficient than SET while assigning values to multiple variables in terms of statements executed, code and network bytes.

What if variable is not populated successfully

If a variable is not successfully populated then behavior for SET and SELECT would be different. Failed assignment may be due to no result returned or any non-compatible value assigned to the variable. In this case, SELECT would preserve the previous value if any, where SET would assign NULL. Because of the difference functionality, both may lead to unexpected results and should be considered carefully.

This is shown in following script

We can see that part 1 generates NULL when no value is returned for populating variable. Where as part 2 produces the previous value that is preserved after failed assignment of the variable. This situation may lead to unexpected results and requires consideration.

Following the standards

Using SELECT may look like a better choice in specific scenarios, but be aware that using SELECT for assigning values to variables is not included in the ANSI standards. If you are following standards for code migration purposes, then avoid using SELECT and use SET instead.

Best practice suggests not to stick to one method. Depending on the scenario you may want to use both SET or SELECT.

Following are few scenarios for using SET

  • If you are required to assign a single value directly to variable and no query is involved to fetch value
  • NULL assignments are expected (NULL returned in result set)
  • Standards are meant to be follow for any planned migration
  • Non scalar results are expected and are required to be handled

Using SELECT is efficient and flexible in the following few cases.

  • Multiple variables are being populated by assigning values directly
  • Multiple variables are being populated by single source (table , view)
  • Less coding for assigning multiple variables
  • Use this if you need to get @@ROWCOUNT and @ERROR for last statement executed
  • Click here to look at assigning and declaring variables through single statement along with other new T-SQL enhancements in SQL Server 2008.
  • Click here to read more about @@ROWCOUNT
  • Click here to read more about @@ERROR

sql server categories

About the author

MSSQLTips author Atif Shehzad

Comments For This Article

get free sql tips

Related Content

How to use @@ROWCOUNT in SQL Server

SQL Declare Variable to Define and Use Variables in SQL Server code

SQL Variables in Scripts, Functions, Stored Procedures, SQLCMD and More

Using SQL Variables in SQL Server Code and Queries

The Basics of SQL Server Variables

Nullability settings with select into and variables

SQL Server 2008 Inline variable initialization and Compound assignment

Related Categories

Change Data Capture

Common Table Expressions

Dynamic SQL

Error Handling

Stored Procedures

Transactions

Development

Date Functions

System Functions

JOIN Tables

SQL Server Management Studio

Database Administration

Performance

Performance Tuning

Locking and Blocking

Data Analytics \ ETL

Microsoft Fabric

Azure Data Factory

Integration Services

Popular Articles

SQL Date Format Options with SQL CONVERT Function

SQL Date Format examples using SQL FORMAT Function

SQL Server CROSS APPLY and OUTER APPLY

DROP TABLE IF EXISTS Examples for SQL Server

SQL Server Cursor Example

SQL CASE Statement in Where Clause to Filter Based on a Condition or Expression

SQL NOT IN Operator

Rolling up multiple rows into a single row and column for SQL Server data

SQL Convert Date to YYYYMMDD

Resolving could not open a connection to SQL Server errors

Format numbers in SQL Server

SQL Server PIVOT and UNPIVOT Examples

Script to retrieve SQL Server database backup history and no backups

SQL Server Loop through Table Rows without Cursor

How to install SQL Server 2022 step by step

An Introduction to SQL Triggers

List SQL Server Login and User Permissions with fn_my_permissions

How to monitor backup and restore progress in SQL Server

Using MERGE in SQL Server to insert, update and delete at the same time

Searching between two date values in SQL Server

SQL Tutorial

SQLTutorial.net – Learn SQL

SQL String Functions

SQL String functions are a set of built-in functions that are used to manipulate strings or character data in SQL. These functions can be used to extract, transform and manipulate data stored in character data type columns.

Here are some of the most commonly used SQL string functions :

CONCAT This function is used to concatenate two or more strings into a single string.

CONCAT_WS It is used to concatenate multiple strings or expressions into a single string, separating each element with a specified separator. The syntax typically involves providing the separator as the first argument, followed by the strings or expressions to be concatenated. Unlike the regular CONCAT function, CONCAT_WS allows you to avoid explicitly handling separator placement between elements, making it particularly useful when dealing with lists or combining values with a consistent separator.

SUBSTRING This function is used to extract a substring from a given string.

LEN This function is used to get the length of a string.

REPLACE This function is used to replace a part of a string with another string.

UPPER This function is used to convert a string to uppercase.

LOWER This function is used to convert a string to lowercase.

TRIM This function is used to remove extra spaces from the beginning and end of a string.

These are just a few of the many SQL string functions that can be used to manipulate strings in a database. Knowing these functions can help you to efficiently query and manipulate data in your database.

  • SQL queries
  • SQL constraints
  • SQL Server autoincrement
  • Select rows with max value
  • SQL HAVING COUNT
  • SQL remove duplicates
  • SQL TCL statements
  • SQL DML statements
  • SQL DDL statements
  • SQL Recursive CTE
  • Dynamic SQL
  • EXEC statement
  • SQL procedure with parameters
  • SQL Procedure vs Function
  • SQL Table-Valued functions
  • SQL Scalar functions
  • SQL User-defined functions
  • ALTER FUNCTION
  • CREATE FUNCTION
  • ALTER PROCEDURE
  • SQL Stored procedures
  • CREATE PROCEDURE
  • Alter trigger
  • SQL SET TRANSACTION
  • SQL SAVEPOINT

Home » SQL String Functions » SQL REPLACE Function: Search and Replace String in Database

SQL REPLACE Function: Search and Replace String in Database

Summary : in this tutorial, you will learn how to use the SQL REPLACE function to search and replace all occurrences of a substring with another substring in a given string.

Introduction to the SQL REPLACE function

Sometimes, you want to search and replace a substring with a new one in a column e.g., change a dead link to a new one, rename an obsolete product to the new name, etc.

SQL provides a very helpful string function called REPLACE that allows you to replace all occurrences of a substring in a string with a new substring.

The following illustrates the syntax of the REPLACE function:

The REPLACE function will search for all occurrences of the old_substring and replace it with the new_string .

The following statement replaces all the occurrences of bar with foo so the result is bar bar bar .

Note that the REPLACE function searches for the substring in the case sensitive manner. For example, the following statement replaces foo with bar , the FOO will not be replaced because it does not match the searched string foo .

If the function cannot find the substring, it does nothing. For example, the following statement returns the original string because it cannot find any occurrences of the substring BAR .

SQL REPLACE with the UPDATE statement

Let’s take a look at the employees table in the sample database .

employees_table

The following statement returns the employee names and their phone numbers.

SQL REPLACE function example

Suppose you want to use the dash  ( - ) character instead of dot ( . ) character to format the phone numbers. In this case, you use the UPDATE  statement to replace the dash character by the dot character in the phone_number column as the following statement:

SQL REPLACE function replace dot with dash

Notice that the above UPDATE statement updates all rows in the employees table.

If you update data in the production system, you should first use a SELECT statement to find the number of rows affected before doing the mass update.

For example, the following statement updates the email of employees from sqltutorial.org to acme.com for the employee id 100:

Let’s check the result.

SQL REPLACE change email

It works as expected. So we can apply the changes to all rows by removing the WHERE clause.

Notice that it is easy to make a mistake to use the column name as a literal string for the first argument of the REPLACE  function as follows.

Your intention is to replace the sqltutorial.org in the email column with acme.com . However, this statement will update all values in the email columns to email  because the result of the following expression is a literal string email.

In this tutorial, you have learned how to use the SQL REPLACE function to search and replace all occurrences of a substring with a new string.

14.8 String Functions and Operators

Table 14.12 String Functions and Operators

String-valued functions return NULL if the length of the result would be greater than the value of the max_allowed_packet system variable. See Section 7.1.1, “Configuring the Server” .

For functions that operate on string positions, the first position is numbered 1.

For functions that take length arguments, noninteger arguments are rounded to the nearest integer.

ASCII( str )

Returns the numeric value of the leftmost character of the string str . Returns 0 if str is the empty string. Returns NULL if str is NULL . ASCII() works for 8-bit characters.

See also the ORD() function.

Returns a string representation of the binary value of N , where N is a longlong ( BIGINT ) number. This is equivalent to CONV( N ,10,2) . Returns NULL if N is NULL .

BIT_LENGTH( str )

Returns the length of the string str in bits. Returns NULL if str is NULL .

CHAR( N ,... [USING charset_name ])

CHAR() interprets each argument N as an integer and returns a string consisting of the characters given by the code values of those integers. NULL values are skipped.

By default, CHAR() returns a binary string. To produce a string in a given character set, use the optional USING clause:

If USING is given and the result string is illegal for the given character set, a warning is issued. Also, if strict SQL mode is enabled, the result from CHAR() becomes NULL .

If CHAR() is invoked from within the mysql client, binary strings display using hexadecimal notation, depending on the value of the --binary-as-hex . For more information about that option, see Section 6.5.1, “mysql — The MySQL Command-Line Client” .

CHAR() arguments larger than 255 are converted into multiple result bytes. For example, CHAR(256) is equivalent to CHAR(1,0) , and CHAR(256*256) is equivalent to CHAR(1,0,0) :

CHAR_LENGTH( str )

Returns the length of the string str , measured in code points. A multibyte character counts as a single code point. This means that, for a string containing two 3-byte characters, LENGTH() returns 6 , whereas CHAR_LENGTH() returns 2 , as shown here:

CHAR_LENGTH() returns NULL if str is NULL .

CHARACTER_LENGTH( str )

CHARACTER_LENGTH() is a synonym for CHAR_LENGTH() .

CONCAT( str1 , str2 ,...)

Returns the string that results from concatenating the arguments. May have one or more arguments. If all arguments are nonbinary strings, the result is a nonbinary string. If the arguments include any binary strings, the result is a binary string. A numeric argument is converted to its equivalent nonbinary string form.

CONCAT() returns NULL if any argument is NULL .

For quoted strings, concatenation can be performed by placing the strings next to each other:

If CONCAT() is invoked from within the mysql client, binary string results display using hexadecimal notation, depending on the value of the --binary-as-hex . For more information about that option, see Section 6.5.1, “mysql — The MySQL Command-Line Client” .

CONCAT_WS( separator , str1 , str2 ,...)

CONCAT_WS() stands for Concatenate With Separator and is a special form of CONCAT() . The first argument is the separator for the rest of the arguments. The separator is added between the strings to be concatenated. The separator can be a string, as can the rest of the arguments. If the separator is NULL , the result is NULL .

CONCAT_WS() does not skip empty strings. However, it does skip any NULL values after the separator argument.

ELT( N , str1 , str2 , str3 ,...)

ELT() returns the N th element of the list of strings: str1 if N = 1 , str2 if N = 2 , and so on. Returns NULL if N is less than 1 , greater than the number of arguments, or NULL . ELT() is the complement of FIELD() .

EXPORT_SET( bits , on , off [, separator [, number_of_bits ]])

Returns a string such that for every bit set in the value bits , you get an on string and for every bit not set in the value, you get an off string. Bits in bits are examined from right to left (from low-order to high-order bits). Strings are added to the result from left to right, separated by the separator string (the default being the comma character , ). The number of bits examined is given by number_of_bits , which has a default of 64 if not specified. number_of_bits is silently clipped to 64 if larger than 64. It is treated as an unsigned integer, so a value of −1 is effectively the same as 64.

FIELD( str , str1 , str2 , str3 ,...)

Returns the index (position) of str in the str1 , str2 , str3 , ... list. Returns 0 if str is not found.

If all arguments to FIELD() are strings, all arguments are compared as strings. If all arguments are numbers, they are compared as numbers. Otherwise, the arguments are compared as double.

If str is NULL , the return value is 0 because NULL fails equality comparison with any value. FIELD() is the complement of ELT() .

FIND_IN_SET( str , strlist )

Returns a value in the range of 1 to N if the string str is in the string list strlist consisting of N substrings. A string list is a string composed of substrings separated by , characters. If the first argument is a constant string and the second is a column of type SET , the FIND_IN_SET() function is optimized to use bit arithmetic. Returns 0 if str is not in strlist or if strlist is the empty string. Returns NULL if either argument is NULL . This function does not work properly if the first argument contains a comma ( , ) character.

FORMAT( X , D [, locale ])

Formats the number X to a format like '#,###,###.##' , rounded to D decimal places, and returns the result as a string. If D is 0 , the result has no decimal point or fractional part. If X or D is NULL , the function returns NULL .

The optional third parameter enables a locale to be specified to be used for the result number's decimal point, thousands separator, and grouping between separators. Permissible locale values are the same as the legal values for the lc_time_names system variable (see Section 12.16, “MySQL Server Locale Support” ). If the locale is NULL or not specified, the default locale is 'en_US' .

FROM_BASE64( str )

Takes a string encoded with the base-64 encoded rules used by TO_BASE64() and returns the decoded result as a binary string. The result is NULL if the argument is NULL or not a valid base-64 string. See the description of TO_BASE64() for details about the encoding and decoding rules.

If FROM_BASE64() is invoked from within the mysql client, binary strings display using hexadecimal notation. You can disable this behavior by setting the value of the --binary-as-hex to 0 when starting the mysql client. For more information about that option, see Section 6.5.1, “mysql — The MySQL Command-Line Client” .

HEX( str ) , HEX( N )

For a string argument str , HEX() returns a hexadecimal string representation of str where each byte of each character in str is converted to two hexadecimal digits. (Multibyte characters therefore become more than two digits.) The inverse of this operation is performed by the UNHEX() function.

For a numeric argument N , HEX() returns a hexadecimal string representation of the value of N treated as a longlong ( BIGINT ) number. This is equivalent to CONV( N ,10,16) . The inverse of this operation is performed by CONV(HEX( N ),16,10) .

For a NULL argument, this function returns NULL .

INSERT( str , pos , len , newstr )

Returns the string str , with the substring beginning at position pos and len characters long replaced by the string newstr . Returns the original string if pos is not within the length of the string. Replaces the rest of the string from position pos if len is not within the length of the rest of the string. Returns NULL if any argument is NULL .

This function is multibyte safe.

INSTR( str , substr )

Returns the position of the first occurrence of substring substr in string str . This is the same as the two-argument form of LOCATE() , except that the order of the arguments is reversed.

This function is multibyte safe, and is case-sensitive only if at least one argument is a binary string. If either argument is NULL , this functions returns NULL .

LCASE( str )

LCASE() is a synonym for LOWER() .

LCASE() used in a view is rewritten as LOWER() when storing the view's definition. (Bug #12844279)

LEFT( str , len )

Returns the leftmost len characters from the string str , or NULL if any argument is NULL .

LENGTH( str )

Returns the length of the string str , measured in bytes. A multibyte character counts as multiple bytes. This means that for a string containing five 2-byte characters, LENGTH() returns 10 , whereas CHAR_LENGTH() returns 5 . Returns NULL if str is NULL .

The Length() OpenGIS spatial function is named ST_Length() in MySQL.

LOAD_FILE( file_name )

Reads the file and returns the file contents as a string. To use this function, the file must be located on the server host, you must specify the full path name to the file, and you must have the FILE privilege. The file must be readable by the server and its size less than max_allowed_packet bytes. If the secure_file_priv system variable is set to a nonempty directory name, the file to be loaded must be located in that directory. (Prior to MySQL 8.0.17, the file must be readable by all, not just readable by the server.)

If the file does not exist or cannot be read because one of the preceding conditions is not satisfied, the function returns NULL .

The character_set_filesystem system variable controls interpretation of file names that are given as literal strings.

LOCATE( substr , str ) , LOCATE( substr , str , pos )

The first syntax returns the position of the first occurrence of substring substr in string str . The second syntax returns the position of the first occurrence of substring substr in string str , starting at position pos . Returns 0 if substr is not in str . Returns NULL if any argument is NULL .

This function is multibyte safe, and is case-sensitive only if at least one argument is a binary string.

LOWER( str )

Returns the string str with all characters changed to lowercase according to the current character set mapping, or NULL if str is NULL . The default character set is utf8mb4 .

LOWER() (and UPPER() ) are ineffective when applied to binary strings ( BINARY , VARBINARY , BLOB ). To perform lettercase conversion of a binary string, first convert it to a nonbinary string using a character set appropriate for the data stored in the string:

For collations of Unicode character sets, LOWER() and UPPER() work according to the Unicode Collation Algorithm (UCA) version in the collation name, if there is one, and UCA 4.0.0 if no version is specified. For example, utf8mb4_0900_ai_ci and utf8mb3_unicode_520_ci work according to UCA 9.0.0 and 5.2.0, respectively, whereas utf8mb3_unicode_ci works according to UCA 4.0.0. See Section 12.10.1, “Unicode Character Sets” .

LCASE() used within views is rewritten as LOWER() .

LPAD( str , len , padstr )

Returns the string str , left-padded with the string padstr to a length of len characters. If str is longer than len , the return value is shortened to len characters.

Returns NULL if any of its arguments are NULL .

LTRIM( str )

Returns the string str with leading space characters removed. Returns NULL if str is NULL .

MAKE_SET( bits , str1 , str2 ,...)

Returns a set value (a string containing substrings separated by , characters) consisting of the strings that have the corresponding bit in bits set. str1 corresponds to bit 0, str2 to bit 1, and so on. NULL values in str1 , str2 , ... are not appended to the result.

MID( str , pos , len )

MID( str , pos , len ) is a synonym for SUBSTRING( str , pos , len ) .

Returns a string representation of the octal value of N , where N is a longlong ( BIGINT ) number. This is equivalent to CONV( N ,10,8) . Returns NULL if N is NULL .

OCTET_LENGTH( str )

OCTET_LENGTH() is a synonym for LENGTH() .

If the leftmost character of the string str is a multibyte character, returns the code for that character, calculated from the numeric values of its constituent bytes using this formula:

If the leftmost character is not a multibyte character, ORD() returns the same value as the ASCII() function. The function returns NULL if str is NULL .

POSITION( substr IN str )

POSITION( substr IN str ) is a synonym for LOCATE( substr , str ) .

QUOTE( str )

Quotes a string to produce a result that can be used as a properly escaped data value in an SQL statement. The string is returned enclosed by single quotation marks and with each instance of backslash ( \ ), single quote ( ' ), ASCII NUL , and Control+Z preceded by a backslash. If the argument is NULL , the return value is the word “ NULL ” without enclosing single quotation marks.

For comparison, see the quoting rules for literal strings and within the C API in Section 11.1.1, “String Literals” , and mysql_real_escape_string_quote() .

REPEAT( str , count )

Returns a string consisting of the string str repeated count times. If count is less than 1, returns an empty string. Returns NULL if str or count is NULL .

REPLACE( str , from_str , to_str )

Returns the string str with all occurrences of the string from_str replaced by the string to_str . REPLACE() performs a case-sensitive match when searching for from_str .

This function is multibyte safe. It returns NULL if any of its arguments are NULL .

REVERSE( str )

Returns the string str with the order of the characters reversed, or NULL if str is NULL .

RIGHT( str , len )

Returns the rightmost len characters from the string str , or NULL if any argument is NULL .

RPAD( str , len , padstr )

Returns the string str , right-padded with the string padstr to a length of len characters. If str is longer than len , the return value is shortened to len characters. If str , padstr , or len is NULL , the function returns NULL .

RTRIM( str )

Returns the string str with trailing space characters removed.

This function is multibyte safe, and returns NULL if str is NULL .

SOUNDEX( str )

Returns a soundex string from str , or NULL if str is NULL . Two strings that sound almost the same should have identical soundex strings. A standard soundex string is four characters long, but the SOUNDEX() function returns an arbitrarily long string. You can use SUBSTRING() on the result to get a standard soundex string. All nonalphabetic characters in str are ignored. All international alphabetic characters outside the A-Z range are treated as vowels.

When using SOUNDEX() , you should be aware of the following limitations:

This function, as currently implemented, is intended to work well with strings that are in the English language only. Strings in other languages may not produce reliable results.

This function is not guaranteed to provide consistent results with strings that use multibyte character sets, including utf-8 . See Bug #22638 for more information.

This function implements the original Soundex algorithm, not the more popular enhanced version (also described by D. Knuth). The difference is that original version discards vowels first and duplicates second, whereas the enhanced version discards duplicates first and vowels second.

expr1 SOUNDS LIKE expr2

This is the same as SOUNDEX( expr1 ) = SOUNDEX( expr2 ) .

Returns a string consisting of N space characters, or NULL if N is NULL .

SUBSTR( str , pos ) , SUBSTR( str FROM pos ) , SUBSTR( str , pos , len ) , SUBSTR( str FROM pos FOR len )

SUBSTR() is a synonym for SUBSTRING() .

SUBSTRING( str , pos ) , SUBSTRING( str FROM pos ) , SUBSTRING( str , pos , len ) , SUBSTRING( str FROM pos FOR len )

The forms without a len argument return a substring from string str starting at position pos . The forms with a len argument return a substring len characters long from string str , starting at position pos . The forms that use FROM are standard SQL syntax. It is also possible to use a negative value for pos . In this case, the beginning of the substring is pos characters from the end of the string, rather than the beginning. A negative value may be used for pos in any of the forms of this function. A value of 0 for pos returns an empty string.

For all forms of SUBSTRING() , the position of the first character in the string from which the substring is to be extracted is reckoned as 1 .

If len is less than 1, the result is the empty string.

SUBSTRING_INDEX( str , delim , count )

Returns the substring from string str before count occurrences of the delimiter delim . If count is positive, everything to the left of the final delimiter (counting from the left) is returned. If count is negative, everything to the right of the final delimiter (counting from the right) is returned. SUBSTRING_INDEX() performs a case-sensitive match when searching for delim .

SUBSTRING_INDEX() returns NULL if any of its arguments are NULL .

TO_BASE64( str )

Converts the string argument to base-64 encoded form and returns the result as a character string with the connection character set and collation. If the argument is not a string, it is converted to a string before conversion takes place. The result is NULL if the argument is NULL . Base-64 encoded strings can be decoded using the FROM_BASE64() function.

Different base-64 encoding schemes exist. These are the encoding and decoding rules used by TO_BASE64() and FROM_BASE64() :

The encoding for alphabet value 62 is '+' .

The encoding for alphabet value 63 is '/' .

Encoded output consists of groups of 4 printable characters. Each 3 bytes of the input data are encoded using 4 characters. If the last group is incomplete, it is padded with '=' characters to a length of 4.

A newline is added after each 76 characters of encoded output to divide long output into multiple lines.

Decoding recognizes and ignores newline, carriage return, tab, and space.

TRIM([{BOTH | LEADING | TRAILING} [ remstr ] FROM] str ) , TRIM([ remstr FROM] str )

Returns the string str with all remstr prefixes or suffixes removed. If none of the specifiers BOTH , LEADING , or TRAILING is given, BOTH is assumed. remstr is optional and, if not specified, spaces are removed.

UCASE( str )

UCASE() is a synonym for UPPER() .

UCASE() used within views is rewritten as UPPER() .

UNHEX( str )

For a string argument str , UNHEX( str ) interprets each pair of characters in the argument as a hexadecimal number and converts it to the byte represented by the number. The return value is a binary string.

The characters in the argument string must be legal hexadecimal digits: '0' .. '9' , 'A' .. 'F' , 'a' .. 'f' . If the argument contains any nonhexadecimal digits, or is itself NULL , the result is NULL :

A NULL result can also occur if the argument to UNHEX() is a BINARY column, because values are padded with 0x00 bytes when stored but those bytes are not stripped on retrieval. For example, '41' is stored into a CHAR(3) column as '41 ' and retrieved as '41' (with the trailing pad space stripped), so UNHEX() for the column value returns X'41' . By contrast, '41' is stored into a BINARY(3) column as '41\0' and retrieved as '41\0' (with the trailing pad 0x00 byte not stripped). '\0' is not a legal hexadecimal digit, so UNHEX() for the column value returns NULL .

For a numeric argument N , the inverse of HEX( N ) is not performed by UNHEX() . Use CONV(HEX( N ),16,10) instead. See the description of HEX() .

If UNHEX() is invoked from within the mysql client, binary strings display using hexadecimal notation, depending on the value of the --binary-as-hex . For more information about that option, see Section 6.5.1, “mysql — The MySQL Command-Line Client” .

UPPER( str )

Returns the string str with all characters changed to uppercase according to the current character set mapping, or NULL if str is NULL . The default character set is utf8mb4 .

See the description of LOWER() for information that also applies to UPPER() . This included information about how to perform lettercase conversion of binary strings ( BINARY , VARBINARY , BLOB ) for which these functions are ineffective, and information about case folding for Unicode character sets.

WEIGHT_STRING( str [AS {CHAR|BINARY}( N )] [ flags ])

This function returns the weight string for the input string. The return value is a binary string that represents the comparison and sorting value of the string, or NULL if the argument is NULL . It has these properties:

If WEIGHT_STRING( str1 ) = WEIGHT_STRING( str2 ) , then str1 = str2 ( str1 and str2 are considered equal)

If WEIGHT_STRING( str1 ) < WEIGHT_STRING( str2 ) , then str1 < str2 ( str1 sorts before str2 )

WEIGHT_STRING() is a debugging function intended for internal use. Its behavior can change without notice between MySQL versions. It can be used for testing and debugging of collations, especially if you are adding a new collation. See Section 12.14, “Adding a Collation to a Character Set” .

This list briefly summarizes the arguments. More details are given in the discussion following the list.

str : The input string expression.

AS clause: Optional; cast the input string to a given type and length.

flags : Optional; unused.

The input string, str , is a string expression. If the input is a nonbinary (character) string such as a CHAR , VARCHAR , or TEXT value, the return value contains the collation weights for the string. If the input is a binary (byte) string such as a BINARY , VARBINARY , or BLOB value, the return value is the same as the input (the weight for each byte in a binary string is the byte value). If the input is NULL , WEIGHT_STRING() returns NULL .

The preceding examples use HEX() to display the WEIGHT_STRING() result. Because the result is a binary value, HEX() can be especially useful when the result contains nonprinting values, to display it in printable form:

For non- NULL return values, the data type of the value is VARBINARY if its length is within the maximum length for VARBINARY , otherwise the data type is BLOB .

The AS clause may be given to cast the input string to a nonbinary or binary string and to force it to a given length:

AS CHAR( N ) casts the string to a nonbinary string and pads it on the right with spaces to a length of N characters. N must be at least 1. If N is less than the length of the input string, the string is truncated to N characters. No warning occurs for truncation.

AS BINARY( N ) is similar but casts the string to a binary string, N is measured in bytes (not characters), and padding uses 0x00 bytes (not spaces).

The flags clause currently is unused.

If WEIGHT_STRING() is invoked from within the mysql client, binary strings display using hexadecimal notation, depending on the value of the --binary-as-hex . For more information about that option, see Section 6.5.1, “mysql — The MySQL Command-Line Client” .

The SQL Substring Function in 5 Examples

Author's photo

  • text functions

Working with text data in SQL? We explain how to get values from any point in a string.

When you think of working with data in SQL, your first thought is probably a database full of numbers and your SQL code doing very fancy calculations. But text is data, too! It’s very common to find text data in databases. Not only do you have to extract it, but often you also have to manipulate it. The functions that let you do so are called text functions .

For anyone who wants to practice SQL functions, I recommend our interactive Standard SQL Functions course. It contains 211 exercises and teaches you how to use common text, numeric, and date-and-time functions in SQL.

One of the common text functions the course covers is SUBSTRING() . In this article, we have five real-life business examples that cover the main uses of this function. Some examples may feel complicated if you’re not familiar with the text functions, so make sure you have the Standard SQL Functions cheat sheet or an overview of SQL text functions by your side.

What Is the SUBSTRING() Function?

SUBSTRING() is a text function that allows you to extract characters from a string. Its syntax is

For the expression argument, you write a string literal or specify a column from which you want to extract the substring. The start argument is an integer indicating the numeric position of the character in the string where the substring begins. The length argument, as the name says, defines the length, an integer value, of the substring to be returned.

How Does SUBSTRING() Work?

The clue is in the function’s name itself. A substring is a string within the main string. Therefore, SUBSTRING() extracts a substring as you specify in its argument.

It works like this:

sql substring function

In the string above, the substring that starts at position 1 and has a length of three characters is ‘STR’ .

Now that we have the principles covered, let me show you several examples. Starting, of course, with the simplest one!

Example 1: Substring From a String Literal

The SUBSTRING() function returns a substring from any string you want. You can write the string explicitly as an argument, like this:

This means: I want to find a substring from the text ‘This is the first substring example’ . The arguments say that the substring starts at the 9th character of the string and that its length is 10 characters.

Let’s see what this code returns:

There’s one column and one row. The substring extracted is ‘the first’ . This is the most basic use of SUBSTRING() ; the code doesn’t even use any tables!

The Employees Table

To show you more interesting examples, I need some data. Let me introduce you to a table named employees .

The table stores information about the employees of an imaginary company Kooler in the following columns:

  • id – The employee’s ID.
  • first_name – The employee’s first name.
  • last_name – The employee’s last name.
  • email – The employee’s email.
  • job_title – The employee’s job title.
  • department – The employee’s department.
  • start_date – The employee’s start date at Kooler.

Here are the first several rows for you to get a sense of the data:

Example 2: Substring From a Column

As you can imagine, writing the string expression explicitly is not the only way to use SUBSTRING() . You can also use it on a column of a table.

Here’s one such example. I want to find the initials of all employees. I use the column email since I know the first two letters of the email address are the initials:

I specify the column email in the function. Getting the first two letters from the email address means the substring starts at the first character for a length of two characters. This returns the desired result:

Example 3: Substring Without the Length Argument

You can omit the length argument in SUBSTRING() , and the function still works. A good example is when you want to show only the year of the employment start date. You see, the column start_date is a little unfriendly for that. This date is written as text data in the MM/YYYY format.

Fortunately, SUBSTRING() solves this problem:

To get the year from the column start_date , defining the start of the substring is enough. In this code, the substring starts from the fourth character. Since I omit the length argument, the length of the substring is however long it is to the end of the string from the fourth character. This is how I easily get the year, as you see below:

Example 4: POSITION() and CHARINDEX()

Back to working with emails. By company policy, the local point of an email address (i.e., the part before ‘@’) is also the employee’s username for logging into all the business applications. You need to extract this username. Here’s how:

The first two arguments are what you have seen already. I want to extract a substring from the column email , and I want it to start from the first character of the string. But now, the length of the substring is different for every employee. How do I tell the function to return all characters before the ‘@’ sign?

I use POSITION() , which is equivalent to CHARINDEX() in SQL Server or MySQL. It locates the specified character in the string and returns its numeric character position. So, the length of the substring that is the employee’s username is equal to POSITION('@' IN email)-1 . Why minus one? Because I don’t want ‘@’ to be included in the employee’s username.

This is the result:

Example 5: LENGTH() + POSITION()

The final example shows you how to find an employee’s job position from the data. Working at Kooler, I know how the job titles are formed: first comes the employee’s seniority, then the department, then the position. For example, ‘Junior Sales Assistant’ means the employee is of junior seniority, is in Sales, and works as an assistant.

Using SQL, I can extract this as a substring:

This is another example of omitting the length argument, albeit a little more complex. As always, I first specify the string column – job_title in this case. After that, I somehow need to find a substring consisting only of the last word in the job title.

I do this by first using LENGTH() . It returns the length of the string in the column job_title . That’s a start; it’s the length of all three words together, including the blank spaces. If I could somehow subtract from it the number of characters in the last word, then I would have the length of the first two words, which would then give me the start of the substring I want.

This is a little complicated because different job position names have different lengths. The only thing that separates the words is the blank space. So, to get the length of the third word in the string, I have to count the number of characters up to the blank space, but from the right .

The POSITION() function saves the day again, but this time combined with REVERSE() . The REVERSE() function reverses the string expression so that ‘Junior Sales Assistant’ becomes ‘tnatsissA selaS roinuJ’. The last word becomes the first one; the word itself is reversed, too, but that doesn’t matter here.

POSITION() finds the position of the blank space after the first word of the reversed string. This equals the place of the blank space before the last word in the original (non-reversed) string.

Phew! Now, if I subtract this number from the total length of the original string, I get the start of the substring, right?

Well, not quite! Using this difference as it produces a substring that includes the last letter of the second word and the blank space before the last word. Why is that?

Two things. The start argument of the SUBSTRING() function is inclusive. Also, POSITION() calculates the position of the blank space, not the number of characters up to the blank space. So, I have to add 2 to get this result:

Now that I have introduced a few other functions, you may want to take a look at some other text functions that may be useful to you.

Learn More About SUBSTRING () and Working With Text Data

Now you know when and how to use SUBSTRING() . It’s time to practice!

There are other text functions, not only SUBSTRING(). You can find them (and much more!) in the Standard SQL Functions course.

You may also like

set string sql

How Do You Write a SELECT Statement in SQL?

set string sql

What Is a Foreign Key in SQL?

set string sql

Enumerate and Explain All the Basic Elements of an SQL Query

  • SQL Cheat Sheet
  • SQL Interview Questions
  • MySQL Interview Questions
  • PL/SQL Interview Questions
  • Learn SQL and Database
  • How to Use SQL DISTINCT and TOP in Same Query?
  • How to Convert Epoch Time to Date in SQL?
  • SQL Query to Make Month Wise Report
  • SQL Query to Convert UTC to Local Time Zone
  • SQL Query to Check Given Format of a Date
  • SQL Query to Add an Agent Parameter in a Database
  • SQL Query to Add Email Validation Using Only One Query
  • SQL Query to List All Databases
  • SQL Query to Select all Records From Employee Table Where Name is Not Specified
  • SQL Query to Get First and Last Day of a Week in a Database
  • SQL Query to Calculate Total Number of Weeks Between Two Specific Dates
  • SQL Query to Calculate Total Number of Days Between Two Specific Dates
  • SQL Query to Convert FLOAT to NVARCHAR
  • Compare and Find Differences Between Two Tables in SQL
  • SQL Full Outer Join Using Left and Right Outer Join and Union Clause
  • Querying Multiple Tables in SQL
  • SQL Query to Find Number of Employees According to Gender Whose DOB is Between a Given Range
  • SQL Query to Print Name of Distinct Employee Whose DOB is Between a Given Range
  • SQL Query to Find Monthly Salary of Employee If Annual Salary is Given

How to Declare a Variable in SQL?

Variables in SQL is a fundamental step towards building efficient and powerful database applications. It enhances the flexibility and efficiency of our database queries. Understanding how to declare variables in SQL is very important to write scalable code. Variables act as placeholders for data which enable us to manipulate and store information within our SQL programs.

In this article, we’ll explore the various methods and best practices for declaring variables in SQL along with the syntax and examples, which help us to write more dynamic and effective queries.

How to Declare a Variable

When working with SQL we may encounter various situations where we need to store and manipulate temporary data within our queries effectively. Variables act as containers for values and enable various operations on the stored data. SQL provides several methods to declare and use variables including the use of the WITH clause, SET command, enhances, and various methods. Below are the methods that are used to declare variables in SQL effectively. The methods are as follows:

Using SET Command

Using WITH Clause

  • Using Scalar Subqueries ,
  • Using Temporary Tables

1. Using SET Command

Although SQL does not have a built-in SET command like some other database systems, we can use variable assignment using user-defined functions.

num2

Explanation: The query selects the string “ GFG ” and renames it as “ NAME “. Consequently, the output consists of a single column labeled “ NAME ” containing the string “ GFG ” in each row.

2. Using With Clause

The WITH clause is a powerful feature in SQL that allows defining temporary result sets within a query. Variables can be declared and assigned values within the WITH clause.

Explanation: The output shows a virtual table named “ Customers ” created using a Common Table Expression (CTE) . It consists of a single column labeled “name”, containing the value “ GFG “. The SELECT statement retrieves all rows from this “ Customers ” table, displaying the single row with “ GFG ” as the name.

3. Using Temporary Variables

Temporary tables can be used to store and manipulate data within a session. We can take advantage of temporary tables to mimic variable declaration.

Screenshot-2024-03-20-162057

Using Temporary Variable

Explanation: The output displays a temporary table named “ Temp_Table” created with two columns: “ num ” of type INTEGER and “ name ” of type STRING . One row is inserted with values (23, “GFG”). The subsequent SELECT statement retrieves and displays the values from the “ num ” and “ name ” columns of “ Temp_Table “.

4. Using Subqueries

Subqueries in SQL provide a versatile tool for embedding queries within queries. This article delves into their application in assigning values to variables within SQLite databases, offering insights and examples for effective database manipulation.

n

Using Subqueries

Explanation: The output simply returns the value 23 as “ num ” using a subquery within the SELECT statement . It assigns the result of the inner query directly to the column “num” in the outer query’s result set.

In this article, we went through multiple methods to declare variables in SQL , ranging from using with clause to user-defined functions and temporary tables. Each method has its advantages and use cases, depending on the complexity and requirements of our database operations. Understanding these techniques will help you with the flexibility to efficiently manage variables and execute queries in SQL databases. These methods help in flexibility of code.

Please Login to comment...

  • How to Delete Whatsapp Business Account?
  • Discord vs Zoom: Select The Efficienct One for Virtual Meetings?
  • Otter AI vs Dragon Speech Recognition: Which is the best AI Transcription Tool?
  • Google Messages To Let You Send Multiple Photos
  • 30 OOPs Interview Questions and Answers (2024)

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

SQL CAST Function: Everything You Need to Know

Explore the CAST function offered by all database management systems that follow the SQL standard and become a data type conversion wizard.

Dbvisualizer

Casting data from one type to another is a common operation when dealing with a database. The reason is that data conversion underlies several useful operations, such as calculations, function calls, and comparisons. That is why the ANSI standard specifies the SQL CAST function to convert a value from one data type to another.

In this article, you will learn what the CAST SQL function is, how it works, and how to use it in real-world scenarios.

Let's dive in!

What Is CAST in SQL?

CAST in SQL is a function to explicitly convert a value of one data type to another. As part of the SQL standard specification, it is available with the same syntax in different DBMS systems, including MySQL, SQL Server, PostgreSQL, and Oracle. Since database management systems differ, the way CAST is implemented and works under the scenes changes from database to database.

The SQL CAST function accepts a value of any type and attempts to convert it into the specified destination data type. Since not all data conversions are possible, it may raise an error or produce unexpected results during this operation. Refer to the data conversion table of your specific database for more details:

  • MySQL type conversion rules
  • PostgreSQL type conversion
  • SQL Server data type conversion table
  • Oracle type conversion table

SQL data type casting is useful to facilitate comparisons, arithmetic operations, or to comply with particular data type requirements. Let’s now see how to use the CAST SQL function!

CAST SQL Function: Syntax and First Examples

The SQL CAST function has the following syntax:

  • expression is the value you want to convert to the target_data_type type.
  • target_data_type the destination SQL data type expression should be cast to.

Note : target_data_type must be one of the target data types supported by your DBMS. This means that you may not be able to use just any data type. For example, MySQL only supports DATE , DATETIME , DECIMAL , TIME , CHAR , NCHAR , SIGNED , UNSIGNED , and BINARY as target cast data types.

Now, suppose you want to convert the string “123” to an INT. This is how you can with this CAST SQL Server query:

The result will be the number 123

When expression is NULL , the result will be NULL as well.

Keep in mind that CAST is not the only function you have to convert data from one type to another. Depending on the SQL dialect you are using, you may also encounter alternative functions and operators like [expression::target_data_type](https://www.dbvis.com/thetable/casting-in-postgresql-handling-data-type-conversions-effectively/) or <a href="https://learn.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql?view=sql-server-ver16" target="_blank">CONVERT(data_type, expression)</a> . Also, do not forget that most DBMS technologies convert implicit type conversions under the hood when necessary.

SQL CAST In Action

Time to see CAST in action in some real-world use cases!

Since it is not always easy to figure out the data type of an SQL expression, we will use DbVisualizer in this section. This powerful database client enables you to get the data type of an SQL expression simply by clicking on a cell. That nice feature simplifies data conversion a lot!

Consider the following example. 123 could be either a string or a number, but thanks to the indication in the lower left corner you can tell it is a number:

Note the “Number: Unformatted” indication

Now that you are aware of this feat, explore some SQL CAST data conversion examples!

The following queries will be relevant to MySQL, but you can easily adapt them to any other DBMS.

Float to Integer

You have the decimal number 42.69 and you want to convert it to its integer representation. Here is how you can do it:

In MySQL, the result will be:

Note that how the decimal-to-integer conversion occurs depends on the database technology you are using. Some round to the nearest integer, while others take only the integer part.

Integer to Float

When dealing with arithmetic calculations, it may be necessary to convert an integer to a decimal to obtain the desired results without truncation. Consider the cast as decimal SQL example below:

The result will be the decimal representation of 3 :

As shown by DbVisualizer, that 3 is a decimal number

String to Date

Another common scenario is to convert a string to a date. You can achieve that with the SQL cast as date example below:

The result will be the DATE :

The reusling string is a date in the “yyyy-MM-dd” format

If you write an invalid date string, the result will be

Note how an invalid date strings lead to a NULL result

Keep in mind that databases usually offer specific dates for string-to-date and date-to-string conversions. These offer more options and typically represent a better alternative than the CAST SQL function. For more info, read our guide on date formatting in Postgres .

Integer to String

DBMS systems generally offer a lot of functions and operators for string data types. This is why you may need to cast an integer to a string in SQL. Achieve that with the following MySQL query:

The result will be the text representation of 42 :

“42” is text

Awesome! You are now a CAST SQL expert!

SQL CAST Function: Best Practices

Here is a list of best practices for the CAST function in SQL:

  • Convert data only when required as cast operations can lead to overhead, data loss, and inaccurate results.
  • Consult the documentation to learn which data types can be converted between them and which cannot.
  • Use a database client such as DbVisualizer to verify that the data has been converted to the desired type with a single click.
  • Use specific cast date SQL functions for more control over the result.
  • Pay attention to automatic rounding when converting from float to integer to avoid data truncation.

In this guide, you understood what the CAST function in SQL is and how it works. You now know that CAST is a standard data type conversion function available in most DBMS technologies. Thanks to the usage examples shown here, you have also learned how and when to use it.

Figuring out the type of an SQL value is not always easy. Thanks to a powerful database client like DbVisualizer, that becomes a piece of cake! With a single click on a cell, you can get instant feedback on the data type of the value stored in it. This is just one of the many features supported by this powerful tool, which also includes advanced query optimization capabilities and automatic ERD-like schema generation. Try DbVisualizer for free today!

Is the SQL CAST function part of the standard SQL specification?

Yes, the SQL CAST function is part of the standard SQL specification. It provides a consistent method for converting data types across different database systems, ensuring portability and interoperability. However, specific implementations may slightly vary in implementation and behavior.

What DBMS technologies support CAST?

Most major database management systems support the CAST function, including MySQL, PostgreSQL, SQL Server, Oracle, and SQLite.

Can you cast a type to all other types in SQL?

No, you cannot cast a data type to all other types in SQL. Data type conversions are limited to compatible types defined by the database system. Attempting to cast a type to an incompatible or unsupported type may result in errors or produce unexpected results. Read the documentation of your specific database system for information on supported data type casting.

What is the difference between CAST and the :: operator in PostgreSQL?

In PostgreSQL, both CAST and the :: operator are used for data type conversion. However, CAST is SQL-standard compliant and provides more readability and portability across different database systems. Instead, the :: operator is a PostgreSQL-specific shorthand for type casting, commonly used for query readability.

What is the difference between the SQL CAST function and the SQL CONVERT function?

Both CAST and CONVERT are SQL functions to convert data types, but they differ in syntax and usage. CAST is standard SQL supported across database systems, while CONVERT is database-specific. Refer to the documentation of the SQL dialect you are using for more details on their availability.

Dbvis download link img

Antonello is a software engineer, and often refers to himself as a technology bishop. His mission is to spread knowledge through writing.

The Table Icon

PostgreSQL Upsert: INSERT ON CONFLICT Guide

Insert into sql clause, postgres text vs varchar: comparing string data types, alter table add column in sql: a comprehensive guide, schemas in postgresql, sql server for mac: the ultimate guide to the best sql server client, 5 ways to split a string in postgresql, mysql ifnull – everything you need to know, postgresql case: a comprehensive guide, sql ddl: the definitive guide on data definition language.

The content provided on dbvis.com/thetable, including but not limited to code and examples, is intended for educational and informational purposes only. We do not make any warranties or representations of any kind.  Read more here .

We use cookies to ensure that we give you the best experience on our website. However you can change your cookie settings at any time in your browser settings. Please find our cookie policy here ↗

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

Variables (Transact-SQL)

  • 14 contributors

A Transact-SQL local variable is an object that can hold a single data value of a specific type. Variables in batches and scripts are typically used:

  • As a counter either to count the number of times a loop is performed or to control how many times the loop is performed.
  • To hold a data value to be tested by a control-of-flow statement.
  • To save a data value to be returned by a stored procedure return code or function return value.
  • The names of some Transact-SQL system functions begin with two at signs (@@). Although in earlier versions of SQL Server, the @@functions are referred to as global variables, @@functions aren't variables, and they don't have the same behaviors as variables. The @@functions are system functions, and their syntax usage follows the rules for functions.
  • You can't use variables in a view.
  • Changes to variables aren't affected by the rollback of a transaction.

The following script creates a small test table and populates it with 26 rows. The script uses a variable to do three things:

  • Control how many rows are inserted by controlling how many times the loop is executed.
  • Supply the value inserted into the integer column.
  • Function as part of the expression that generates letters to be inserted into the character column.

Declaring a Transact-SQL Variable

The DECLARE statement initializes a Transact-SQL variable by:

  • Assigning a name. The name must have a single @ as the first character.
  • Assigning a system-supplied or user-defined data type and a length. For numeric variables, a precision and scale are also assigned. For variables of type XML, an optional schema collection may be assigned.
  • Setting the value to NULL.

For example, the following DECLARE statement creates a local variable named @mycounter with an int data type.

To declare more than one local variable, use a comma after the first local variable defined, and then specify the next local variable name and data type.

For example, the following DECLARE statement creates three local variables named @LastName , @FirstName and @StateProvince , and initializes each to NULL:

The scope of a variable is the range of Transact-SQL statements that can reference the variable. The scope of a variable lasts from the point it is declared until the end of the batch or stored procedure in which it is declared. For example, the following script generates a syntax error because the variable is declared in one batch and referenced in another:

Variables have local scope and are only visible within the batch or procedure where they are defined. In the following example, the nested scope created for execution of sp_executesql does not have access to the variable declared in the higher scope and returns and error.

Setting a Value in a Transact-SQL Variable

When a variable is first declared, its value is set to NULL. To assign a value to a variable, use the SET statement. This is the preferred method of assigning a value to a variable. A variable can also have a value assigned by being referenced in the select list of a SELECT statement.

To assign a variable a value by using the SET statement, include the variable name and the value to assign to the variable. This is the preferred method of assigning a value to a variable. The following batch, for example, declares two variables, assigns values to them, and then uses them in the WHERE clause of a SELECT statement:

A variable can also have a value assigned by being referenced in a select list. If a variable is referenced in a select list, it should be assigned a scalar value or the SELECT statement should only return one row. For example:

If there are multiple assignment clauses in a single SELECT statement, SQL Server does not guarantee the order of evaluation of the expressions. Note that effects are only visible if there are references among the assignments.

If a SELECT statement returns more than one row and the variable references a non-scalar expression, the variable is set to the value returned for the expression in the last row of the result set. For example, in the following batch @EmpIDVariable is set to the BusinessEntityID value of the last row returned, which is 1:

Declare @local_variable SET @local_variable SELECT @local_variable Expressions (Transact-SQL) Compound Operators (Transact-SQL)

Was this page helpful?

Coming soon: Throughout 2024 we will be phasing out GitHub Issues as the feedback mechanism for content and replacing it with a new feedback system. For more information see: https://aka.ms/ContentUserFeedback .

Submit and view feedback for

Additional resources

Search code, repositories, users, issues, pull requests...

Provide feedback.

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly.

To see all available qualifiers, see our documentation .

  • Notifications

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement . We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Connection string property "Connection Timeout" is not respected. #2430

@dmytro-gokun

dmytro-gokun commented Mar 26, 2024

@roji

roji commented Mar 26, 2024 • edited

  • 👍 1 reaction

Sorry, something went wrong.

roji commented Mar 26, 2024

@vonzshik

vonzshik commented Mar 26, 2024

That thread synchronously goes through every single open request and tries to open a physical connection:

SqlClient/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/ProviderBase/DbConnectionPool.cs

Lines 1046 to 1072 in 30cd171

The way opening a physical connection works is that there are multiple handles (one for getting a connection from a pool, one to open a physical connection, one for errors), so SqlClient just waits for any of them to fire:

Lines 1189 to 1216 in 30cd171

At this point timeout ( waitForMultipleObjectsTimeout in this case) is 0 so WaitHandle.WaitAny should immediately return a timeout error. But because connections are open sequentially, the handle responsible for opening a physical connection is always set and WaitHandle.WaitAny returns that handle. Essentially, what's happening is:

  • Pool's thread gets a connection request from the queue
  • Takes a semaphore to open a physical connection
  • Tries (and fails) to open a physical connection
  • Releases a semaphore

dmytro-gokun commented Mar 26, 2024 • edited

@DavoudEshtehari

cheenamalhotra commented Mar 27, 2024

Dmytro-gokun commented mar 27, 2024.

No branches or pull requests

@dmytro-gokun

SQL Tutorial

Sql database, sql references, sql examples, sql server substring() function.

Extract 3 characters from a string, starting in position 1:

Definition and Usage

The SUBSTRING() function extracts some characters from a string.

Parameter Values

Technical details, more examples.

Extract 5 characters from the "CustomerName" column, starting in position 1:

Extract 100 characters from a string, starting in position 1:

Get Certified

COLOR PICKER

colorpicker

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

[email protected]

Top Tutorials

Top references, top examples, get certified.

IMAGES

  1. SQL String Functions

    set string sql

  2. SQL String Functions with Syntax and Examples

    set string sql

  3. SQL Tutorial #28

    set string sql

  4. EXEC SQL overview and examples

    set string sql

  5. [SQL Basic] How to work with String Functions in SQL —My SQL CONCAT

    set string sql

  6. Armazenando uma string diferente do inglês na tabela

    set string sql

VIDEO

  1. ALL STRING SQL FUNCTION

  2. String Functions in SQL-Offline Batch

  3. 06 SQL String Function

  4. PE13 Autolisp Fungsi Penanganan String / String Handling Function

  5. קורס SQL שיעור 13 -STRING FUNCTION

  6. SQL ALL STRING FUNCTIONS

COMMENTS

  1. sql

    With using this approach you can ensure that the data values being passed into the query are the correct datatypes and avoind use of more quotes. DECLARE @sqlCommand nvarchar(1000) DECLARE @columnList varchar(75) DECLARE @city varchar(75) SET @columnList = 'CustomerID, ContactName, City'. SET @city = 'London'.

  2. 5 SQL Functions for Manipulating Strings

    SQL String Functions: REPLACE. REPLACE(entry_char, string_searching, string_replace) SQL string.It returns an entry_char where the value of string_searching is replaced with string_replace.If the string_replace value is null, then every value matching string_searching. is deleted from the entry string.. Let's see two examples of REPLACE at work. Suppose we want to update part of a record:

  3. String Functions (Transact-SQL)

    The following scalar functions perform an operation on a string input value and return a string or numeric value: All built-in string functions except FORMAT are deterministic. This means they return the same value any time they are called with a specific set of input values. For more information about function determinism, see Deterministic ...

  4. SQL SET

    string functions: ascii char_length character_length concat concat_ws field find_in_set format insert instr lcase left length locate lower lpad ltrim mid position repeat replace reverse right rpad rtrim space strcmp substr substring substring_index trim ucase upper numeric functions: ... sql set keyword

  5. When to use SET vs SELECT for assigning SQL Server Variables

    Returning values through a query. Whenever you are assigning a query returned value to a variable, SET will accept and assign a scalar (single) value from a query. While SELECT could accept multiple returned values. But after accepting multiple values through a SELECT command you have no way to track which value is present in the variable.

  6. SQL String Functions

    SQL String functions are a set of built-in functions that are used to manipulate strings or character data in SQL. These functions can be used to extract, transform and manipulate data stored in character data type columns. Here are some of the most commonly used SQL string functions:

  7. SET Statements (Transact-SQL)

    The Transact-SQL programming language provides several SET statements that change the current session handling of specific information. The SET statements are grouped into the categories shown in the following table. For information about setting local variables with the SET statement, see SET @local_variable (Transact-SQL).

  8. SQL REPLACE Function: Search and Replace String in Database

    Summary: in this tutorial, you will learn how to use the SQL REPLACE function to search and replace all occurrences of a substring with another substring in a given string.. Introduction to the SQL REPLACE function. Sometimes, you want to search and replace a substring with a new one in a column e.g., change a dead link to a new one, rename an obsolete product to the new name, etc.

  9. MySQL :: MySQL 8.0 Reference Manual :: 13.3.6 The SET Type

    13.3.6 The SET Type. A SET is a string object that can have zero or more values, each of which must be chosen from a list of permitted values specified when the table is created. SET column values that consist of multiple set members are specified with members separated by commas (, ).

  10. 14.8 String Functions and Operators

    String-valued functions return NULL if the length of the result would be greater than the value of the max_allowed_packet system variable. See Section 7.1.1, "Configuring the Server".. For functions that operate on string positions, the first position is numbered 1. For functions that take length arguments, noninteger arguments are rounded to the nearest integer.

  11. How to Concatenate Strings in SQL

    To append a string to another and return one result, use the || operator. This adds two strings from the left and right together and returns one result. If you use the name of the column, don't enclose it in quotes. However, in using a string value as a space or text, enclose it in quotes. In our example, we added a space to first_name and ...

  12. How to use a set of strings in a WHERE statement of SQL?

    You want WHERE ID IN (3, 4, 5), and unfortunately you cannot add a single parameter containing the set of legal values there. Your best option is to either construct the SQL dynamically, or insert the values into a temporary table and do a join (or sub-select in the IN-clause).

  13. SQL

    Following are the string functions defined in SQL: ASCII (): This function is used to find the ASCII value of a character. Syntax: SELECT ascii('t'); Output: 116. CHAR_LENGTH (): Doesn't work for SQL Server. Use LEN () for SQL Server. This function is used to find the length of a word.

  14. + (String Concatenation) (Transact-SQL)

    For more information, see SET CONCAT_NULL_YIELDS_NULL (Transact-SQL). If the result of the concatenation of strings exceeds the limit of 8,000 bytes, the result is truncated. However, if at least one of the strings concatenated is a large value type, truncation does not occur. Examples A. Using string concatenation

  15. How to set variable from a SQL query?

    I'm trying to set a variable from a SQL query: ... My use case was that I wanted to set a variable to a string. All the other answers here show how to set a variable using the output of a SELECT statement. Here's how to do it with a simple string: DECLARE @ModelID varchar(60) = 'Model T' ...

  16. The SQL Substring Function in 5 Examples

    The SUBSTRING() function returns a substring from any string you want. You can write the string explicitly as an argument, like this: SELECT SUBSTRING('This is the first substring example', 9, 10) AS substring_extraction; This means: I want to find a substring from the text 'This is the first substring example'.

  17. SET @local_variable (Transact-SQL)

    The SET statement that assigns a value to the variable returns a single value. When you initialize multiple variables, use a separate SET statement for each local variable. You can use variables only in expressions, not instead of object names or keywords. To construct dynamic Transact-SQL statements, use EXECUTE.

  18. How to Declare a Variable in SQL?

    Explanation: The output simply returns the value 23 as " num " using a subquery within the SELECT statement.It assigns the result of the inner query directly to the column "num" in the outer query's result set. Conclusion. In this article, we went through multiple methods to declare variables in SQL, ranging from using with clause to user-defined functions and temporary tables.

  19. SQL CAST Function: Everything You Need to Know

    CAST SQL Function: Syntax and First Examples. The SQL CAST function has the following syntax: 1 CAST(expression AS target_data_type) Where: expression is the value you want to convert to the target_data_type type. target_data_type the destination SQL data type expression should be cast to. Note: target_data_type must be one of the target data ...

  20. Convert SQL Server result set into string

    8. Both answers are valid, but don't forget to initializate the value of the variable, by default is NULL and with T-SQL: NULL + "Any text" => NULL. It's a very common mistake, don't forget it! Also is good idea to use ISNULL function: SELECT @result = @result + ISNULL(StudentId + ',', '') FROM Student.

  21. Variables (Transact-SQL)

    Declaring a Transact-SQL Variable. The DECLARE statement initializes a Transact-SQL variable by: Assigning a name. The name must have a single @ as the first character. Assigning a system-supplied or user-defined data type and a length. For numeric variables, a precision and scale are also assigned.

  22. Connection string property "Connection Timeout" is not ...

    To achieve this, we set Connection Timeout (and Command Timeout as well, but that is not important for the purpose of this issue). We then expect connection attempt fail fast if the SQL server is not available. This way, our server will be able to do its job even if the SQL server is down for some time. But, somehow this does not work as expected.

  23. How to insert value in SQL string when using SET @sql

    Double quotes are object identifiers in SQL Server you need to use two single quotes to use string leteral. At the moment sql server is treating "N/A" as a column name "N/A". SET @sql = 'SELECT a.ID AS ID, a.UPRN,p.BuildingNo, p.Street,p.Postcode , a.ItemRef,a.SurveyDate , a.OverallRiskCategory , a.SurveyorsComments INTO TEMP_' + @tableName + ' FROM TblAsbestos AS a JOIN TblProperty As p on a ...

  24. SQL Server SUBSTRING() Function

    Set Goal. Get personalized learning journey based on your current skills and goals ... The SUBSTRING() function extracts some characters from a string. Syntax. SUBSTRING(string, start, length) Parameter Values. Parameter Description; string: Required. The string to extract from ... SQL Server (starting with 2008), Azure SQL Database, Azure SQL ...