Ok so I have searched for an answer to this on Technet, to no avail.
I just want to print an integer variable concatenated with two String variables.
This is my code, that doesn't run:
print 'There are ' + #Number + ' alias combinations did not match a record'
It seems like such a basic feature, I couldn't imagine that it is not possible in T-SQL. But if it isn't possible, please just say so. I can't seem to find a straight answer.
declare #x INT = 1 /* Declares an integer variable named "x" with the value of 1 */
PRINT 'There are ' + CAST(#x AS VARCHAR) + ' alias combinations did not match a record' /* Prints a string concatenated with x casted as a varchar */
Numbers have higher precedence than strings so of course the + operators want to convert your strings into numbers before adding.
You could do:
print 'There are ' + CONVERT(varchar(10),#Number) +
' alias combinations did not match a record'
or use the (rather limited) formatting facilities of RAISERROR:
RAISERROR('There are %i alias combinations did not match a record',10,1,#Number)
WITH NOWAIT
If you don't want to manually cast types, you can use the CONCAT-function for this.
PRINT CONCAT('There are ', #Number, ' alias combinations did not match a record')
You can't combine a character string and numeric string. You need to convert the number to a string using either CONVERT or CAST.
For example:
print 'There are ' + cast(#Number as varchar) + ' alias combinations did not match a record'
or
print 'There are ' + convert(varchar,#Number) + ' alias combinations did not match a record'
Double check if you have set and initial value for int and decimal values to be printed.
This sample is printing an empty line
declare #Number INT
print 'The number is : ' + CONVERT(VARCHAR, #Number)
And this sample is printing -> The number is : 1
declare #Number INT = 1
print 'The number is : ' + CONVERT(VARCHAR, #Number)
You may try this one,
declare #Number INT = 5
print 'There are ' + CONVERT(VARCHAR, #Number) + ' alias combinations did not match a record'
Related
In my LastName Column, I have either one name or two names. In some records, I have more than one empty space between the two names.
I will have to select the records which has more than one empty space in the field name.
declare #nam nvarchar(4000)
declare #nam1 nvarchar(4000)
set #nam = 'sam' + ' ' + 'Dev'
set #nam1 = 'ed' + ' ' + ' ' + 'Dev'
In the sample query, i expect the output value should be #nam1.
You can do this using LEN and REPLACE to replace the spaces from string and then get original length - replaced length and then check that in WHERE clause,
SELECT *
FROM
mytTable
WHERE
LEN(LastName)-LEN(REPLACE(LastName, ' ', '')) > 1
I have a column that contains status changes, but I don't want to return the whole string. Is there any way to return just a part of a string after a certain keyword? Every value of the column is in the format of From X to Y where X and Y could be a single word or multiple words. I've looked at the substring and trim functions, but those seem to require knowledge of how many spaces you want to keep.
Edit: I want to keep part Y from the status and get rid of 'From X to'.
You can use a combination of Charindex and Substring and Len to do it.
Try this:
select SUBSTRING(field,charindex('keyword',field), LEN('keyword'))
So this will find Flop and extract it wherever it is in the field
select SUBSTRING('bullflop',charindex('flop','bullflop'), LEN('flop'))
EDIT:
To get the remainder then just set LEN to the field LEN(field)
declare #field varchar(200)
set #field = 'this is bullflop and other such junk'
select SUBSTRING(#field,charindex('flop',#field), LEN(#field) )
EDIT 2:
Now I understand, here is a quick and dirty version...
declare #field varchar(200)
set #field = 'From X to Y'
select Replace(SUBSTRING(#field,charindex('to ',#field), LEN(#field) ), 'to ','')
Returns:
Y
EDIT 3:
Cory is right, this is cleaner.
declare #field varchar(200) = 'From X to Y'
declare #keyword varchar(200) = 'to '
select SUBSTRING(#field,charindex(#keyword,#field) + LEN(#keyword), LEN(#field) )
Other answers are fine, but I like the STUFF() function and it doesn't seem to be well-known, so here's another option:
DECLARE #field VARCHAR(50) = 'From Authorized to Auth Not Needed'
,#keyword VARCHAR(50) = ' to '
SELECT STUFF(#field,1,CHARINDEX(#keyword,#field)+LEN(#keyword),'')
STUFF() is like SUBSTRING() and REPLACE() combined, you feed it a string, a start position and a length, and can replace that with anything or in your case, nothing ''.
From MSDN:
STUFF ( character_expression , start , length , replaceWith_expression )
You can combine a few string functions to do what you want:
DECLARE #Field varchar(100) = 'From A to Z'
DECLARE #Keyword varchar(100) = 'to'
-- Method 1 (Find the keyword, then take the remainder of the string)
SELECT LTRIM(SUBSTRING(#Field,
CHARINDEX(#Keyword, #Field, 0) + LEN(#Keyword), LEN(#Field)))
EDIT:
-- Method 2 (Take from the right the characters up to the keyword)
SELECT RIGHT(#Field, LEN(#Field) - CHARINDEX(#Keyword, #Field, 0) - LEN(#Keyword))
Produces:
'Z'
I have sql query as:
select UJIdentifyer,RecordIdentity,Location,DeptTime,BayNumber,TimingPointIndicatior,
FareStageIndicatior
from QO where UJIdentifyer='139013'
In this query's result, every column's value length is fixed.
Eg. Its mandatory to have Location column with 12 character length.
If it is of 11 then one space should get filled in it, if 10 then 2 spaces.
For this i written :
select UJIdentifyer,case when len(RecordIdentity)=11 then RecordIdentity+''else when len(RecordIdentity)=10 then RecordIdentity+' '.... from QO where UJIdentifyer='139013'
Like this i will have to write 10-12 cases for length matching.
Is there any way through which i can avoid repetition of those similar cases??
Try this :-
case when datalength(Location ) <12
then Location + replicate (' ' ,12-datalength(Location))
END
Example:-
Declare #var varchar(12) = 'SQL'
Select datalength(#var) InitialLength,
case when datalength(#var) <12
then #var + replicate (' ' ,12-datalength(#var))
END as PaddingExtraSpaces,
Datalength(case when datalength(#var) <12
then #var + replicate (' ' ,12-datalength(#var))
END ) FinalLength
Result
IntialLength PaddingExtraSpaces FinalLength
2 SQL 12
Use Datalength to get the number of characters including blanks
Currently, I have a function to get list of columns of 1 table with detail attribute. And off course, there are some tables with a lot of columns. So, the output will be over 10.000 characters.
Here I test like this:
declare #aa nvarchar(max)
set #aa = dbo.fnGetColumnList('Table_Name')
print #aa
The result always has around 4000 characters. It looks like the SQL has truncated it.
What I know that when we declare nvarchar(max), SQL will supports up to 2^32-1 (2GB) for this string. But why it just has around 4000 characters?
When I execute like this:
select dbo.fnGetColumnList('Table_Name')
the result is correct.
And here is the code for the function:
-- get column list from table Mapping
ALTER FUNCTION [dbo].[fnGetColumnList] ( #tblName varchar (30))
RETURNS nvarchar(max)
AS
BEGIN
Declare #sql nvarchar(max)
set #sql = ''
SELECT #sql = #sql + case
when CHARINDEX('char', LOWER([DBType])) > 0 then ', ['+[DBColumn]+']' + ' ['+[DBType]+']' + ' ('+convert(varchar(10),[Length])+') NULL' + CHAR(13)
when CHARINDEX('char', LOWER([DBType])) > 0 then ', ['+[DBColumn]+']' + ' ['+[DBType]+']' + ' NULL' + CHAR(13)
ELSE ', ['+[DBColumn]+']' + ' ['+[DBType]+']' + ' NULL' + CHAR(13)
end FROM dbo.Mapping WHERE [DBTable] = #tblName
return #sql
END
Please advance.
This is almost always a variable assignment type problem, as explained in:
For Nvarchar(Max) I am only getting 4000 characters in TSQL?
If it's not that, then it's probably just the settings of Print to display too few characters:
nvarchar(max) still being truncated
Having looked at the updated code, it seems like it's the second issue, your print is truncating as it's not set to show enough characters.
You should see this by running
SELECT LEN(#aa)
You'll get a number larger than 4000, showing the value is held correctly in the variable.
As explained in Microsoft's nvar and nvarchar docs:
A common misconception is to think that with nchar(n) and nvarchar(n), the n defines the number of characters. However, in nchar(n) and nvarchar(n), the n defines the string length in byte-pairs (0-4,000). n never defines numbers of characters that can be stored. This is similar to the definition of char(n) and varchar(n).
There is an option in SQL Management Studio:
Tools > Options... > Query Results > SQL Server > Results to Text > Maximum number of characters displayed in each column
... Well, not exactly only for PRINT. I need to assign a string variable the value that mixes explicit substrings with integer values (and possibly with other type values). The goal is to get the string for logging.
So far, I use the code like:
DECLARE #msg nvarchar(1000)
...
SET #msg = #procname + 'result = ' + CAST(#result AS nvarchar(5))
+ '; error = ' + CAST(#error AS nvarchar(5))
where the #procname is a string like sp_my_proc:, and the #result and the #error are integer variables. The result should look like (no extra spaces around the numbers, just the minimum length):
sp_my_proc: result = 3; error = 0
The above approach works, but... Is there any better way for converting an integer variable to the string than CAST(#result AS nvarchar(5))? (Consider the magic number 5 being a minor detail to be ignored.)
How do you solve the problem of generating such strings in your code?
Thanks, Petr
In SQL-Server you can use STR() function
http://msdn.microsoft.com/ru-ru/library/ms189527.aspx
The default value for 'length' parameter is 10. Since an integer variable is never longer than 10 symbols (you'd have an overflow) this will always work without errors:
declare #test int
set #test = 333333333
select STR(#test)
Also, take a look at
String.Format like functionality in T-SQL?