I need the text (representation) of a id field in SQL Server 2005. Is there a way, we can generate the textual representation of the id field?
For instance, if the id field reads as 0x00000000000002F0, I need the text value of 0x00000000000002F0 so that I can run SUBSTR operations on the same.
Constraints
I am not allowed to create a stored procedure in the Database (as creation of SP is not allowed)
Thanks!
You can convert unicode strings to binary using
SELECT CONVERT(VARBINARY(40),N'Hello World')
(returns 0x480065006C006C006F00200057006F0072006C006400)
Convert from binary back to unicode using
SELECT CONVERT(NVARCHAR(20), 0x480065006C006C006F00200057006F0072006C006400)
(returns 'Hello World')
Whilst it's not immediately obvious to me why you would want to do this for comparison purposes (as opposed to matching binary values), the undocumented function sys.fn_varbintohexstr should do the trick
declare #vb binary(8)
,#vc varchar(20)
set #vb = 0x00000000000002F0
set #vc = sys.fn_varbintohexstr(#vb)
--prove that this works by concatenating a string to the varchar value
select #vb, '#' + #vc
Related
I have an SQL table with a column which stores xml like this
<AdditionalInfo><RegistrantID>16279</RegistrantID></AdditionalInfo>
I have created a stored procedure like this:
CREATE PROC hr_GetJobStatusByRegistrantId
#registrantId VARCHAR
AS
BEGIN
SELECT TOP 1
[IsSubscribed]
FROM [Hrge].[dbo].[hr_Jobs]
where AdditionalInfo LIKE '%<AdditionalInfo><RegistrantID>%' + #registrantId + '%</RegistrantID></AdditionalInfo>%'
END
When I run this stored procedure, I get null:
exec hr_GetJobStatusByRegistrantId '16279'
If I make this parameter integer then I get convertion to int error.
Please suggest me solution to this.
(Just expanding the comment into an answer)
You should always specify the width of a char or a varchar field, because unless you do the default kicks in. The documentation says:
When n is not specified in a data definition or variable declaration
statement, the default length is 1. When n is not specified when using
the CAST and CONVERT functions, the default length is 30.
which means that in your case you have actually defined #registrantId as VARCHAR(1) so the value of '16279' was trimmed to a single character ('1') and you actually searched for
%<AdditionalInfo><RegistrantID>%1%</RegistrantID></AdditionalInfo>%
in the database. This actually returned the IsSubscribed flag for the first record it found in the DB that had a '1' anywhere in the RegistrantID field. You got lucky that the value was something wrong, so you noticed it.
Additionally you are using % around your parameter. This means that when you search for a RegistrantID of 123, you'll get results for 123, 1234, 2123, 51236, etc, etc, and then just take the first one, whichever that one is (decided by the database, since there is no order clause). It's my guess that you need an exact match, so you should remove those, and just use
'%<AdditionalInfo><RegistrantID>' + #registrantId
+ '</RegistrantID></AdditionalInfo>%'
Also, it the RegistrantId is actually a number, it would be nice if the interface of the procedure reflected that, so it could be defined with
#registrantId int
and then converted to a string in the query
'%<AdditionalInfo><RegistrantID>' + cast(#registrantId as varchar(10))
+ '</RegistrantID></AdditionalInfo>%'
I ran these quires in my SQL server
select cast('<Answers>
<AnswerDescription> ϱπΩ÷√νƞµΔϒᵨλθ→%° </AnswerDescription>
</Answers>' as xml)
select ' ϱπΩ÷√νƞµΔϒᵨλθ→%°'
And got the following results
<Answers>
<AnswerDescription> ?pO÷v??µ??????%° </AnswerDescription>
</Answers>
and
" ?pO÷v??µ??????%°"
How to make my SQL server store or display these values as they are being sent from Application ?
In SQL Server, scalar string values are cast to VARCHAR by default.
Your example can be made to work by indicating that the strings should be treated as NVARCHAR by adding N before the opening single quote:
select cast(N'<Answers>
<AnswerDescription> ϱπΩ÷√νƞµΔϒᵨλθ→%° </AnswerDescription>
</Answers>' as xml)
select N' ϱπΩ÷√νƞµΔϒᵨλθ→%°'
If these strings are being incorrectly stored in the database, it is likely that they are being implicitly cast to VARCHAR at some point during insertion (e.g. INSERT). It's also possible that they are being stored correctly and are cast to VARCHAR on retrieval (e.g. SELECT).
If you add some code to the question showing how you're inserting data and the datatypes of the target tables, it should be possible to provide more detailed assistance.
I believe its problem with incorectly set character set,
change charecter set to UTF8.
I just tested it on my MySQL database, i changed character set to utf8-bin using
ALTER TABLE `tab1` CHANGE `test` `test` VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL
worked without any problem
In connection with data replication from SQL Server to DB2 I have the following question:
On DB2 I have a table containing (for simplicity) two columns: COL1 and COL2.
COL1 is defined as CHAR(20). COL2 is defined as CHAR(10).
COL1 is replicated from SQL by converting a string into hex, e.g. "abcdefghij" to "6162636465666768696A" or "1111111111" to "31313131313131313131" by using the following SQL query:
CONVERT(char(20), cast(#InputString as binary) 2)
where #InputString would be "abedefghij".
In other words COL1 contains the hex value, but as a string (sorry if the wording is incorrect).
I need to convert the hex value back to a string and put this value into COL2.
What should the SQL query be on DB2 to do the convertion? I know how to do this on SQL Server, but not on DB2.
Note: The reason the hex-value is not pre-fixed with "0x" is because style 2 is used in the CONVERT statement.
select hex('A') from sysibm.sysdummy1;
returns 41.
and
select x'41' from sysibm.sysdummy1;
gives you 'A'. So you can put that in a for loop and loop through each pair of hex characters to arrive at your original string. Or you can write your own unhex function.
Taken from dbforums.com /db2/1627076-display-hex-columns.html (edit Nov 2020: original source link is now a spam site)
DB2 has built-in encoding/decoding.
For OPs question, use....
select CAST(ColumnName as char(20) CCSID 37) as ColumnName from TableName where SomeConditionExists
http://www-01.ibm.com/support/knowledgecenter/SSEPEK_10.0.0/com.ibm.db2z10.doc.intro/src/tpc/db2z_introcodepage.dita
This is one of most close topics to subject of my problem:
I have lost 2 days to figure out how to migrate XML files stored in DB2 BLOB field using SQL Developer.
(Yes, migrating to and doing the queries from SQL Developer - we are migrating data to Oracle from DB2, so we were using this tool)!
How to show XML file/string stored in BLOB?
Let's start with, what the problem was:
Data in BLOB was a XML file.
When selected in query, got:
When casted, like:
select CAST(BLOBCOLUMN as VARCHAR(1000)) from TABLE where id = 100;
output was in HEX:
Nothing worked... Not even the solution from the links in this topic.
!NOTHING!
By mistake found a solution:
CREATE FUNCTION in DB2:
CREATE FUNCTION unhex(in VARCHAR(32000) FOR BIT DATA)
RETURNS VARCHAR(32000)
LANGUAGE SQL
CONTAINS SQL
DETERMINISTIC NO EXTERNAL ACTION
BEGIN ATOMIC
RETURN in;
END
Run SELECT:
select UNHEX( CAST(BLOBCOLUMN as VARCHAR(32000) FOR BIT DATA)) from TABLE where id = 100;
Result:
I use this to convert FOR BIT DATA to characters:
cast (colvalue as varchar(2000) ccsid ebcdic for sbcs data)
In SQL Server, the query
SELECT custid, country, region, city
FROM Sales.Customers
WHERE region = N'WA'
what is the meaning of 'N' in the where clause? I remove it, get same result.
It is casting your literal to a Unicode string.
See here for official explanation:
Unicode strings have a format similar to character strings but are preceded by an N identifier (N stands for National Language in the SQL-92 standard).
In many cases, it won't make a difference, unless your literal contains Unicode characters. If it does, and you leave out the explicit cast, it will convert your Unicode characters to a '?':
select 'Ộ', N'Ộ'
---- ----
? Ộ
Unicode string constants that appear in code executed on the server, such as in stored procedures and triggers, must be preceded by the capital letter N. This is true even if the column being referenced is already defined as Unicode. Without the N prefix, the string is converted to the default code page of the database. This may not recognize certain characters.
For example, the stored procedure created in the previous example can be executed on the server in the following way:
EXECUTE Product_Info #name = N'Chain'
The requirement to use the N prefix applies to both string constants that originate on the server and those sent from the client.
'N' stands for National Language and denotes that you are passing a value for NVARCHAR, NCHAR. The data types that accept languages other than English start with N.
Keep in mind that you are not required to wrap your parameter with 'N' for data types like VARCHAR, CHAR because they don't accept Unicode characters.
Any other language such as Arabic, Farsi will be considered as Unicode so they should be manipulated in data types like NVARCHAR and values should be wrapped with 'N' as below:
DECLARE #Name AS NVARCHAR(50);
SET #Name = N'اسم';
PRINT #Name;
This will return:
اسم
If you try without 'N':
DECLARE #Name AS NVARCHAR(50);
SET #Name = 'اسم';
PRINT #Name;
This will return
???
It is because you haven't wrapped the value with 'N' although the data type is NVARCHAR and system doesn't know anything about the word 'اسم'.
How do you add a string to a column in SQL Server?
UPDATE [myTable] SET [myText]=' '+[myText]
That doesn't work:
The data types varchar and text are incompatible in the add operator.
You would use concat on MySQL, but how do you do it on SQL Server?
like said before best would be to set datatype of the column to nvarchar(max), but if that's not possible you can do the following using cast or convert:
-- create a test table
create table test (
a text
)
-- insert test value
insert into test (a) values ('this is a text')
-- the following does not work !!!
update test set a = a + ' and a new text added'
-- but this way it works:
update test set a = cast ( a as nvarchar(max)) + cast (' and a new text added' as nvarchar(max) )
-- test result
select * from test
-- column a contains:
this is a text and a new text added
Stop using the TEXT data type in SQL Server!
It's been deprecated since the 2005 version. Use VARCHAR(MAX) instead, if you need more than 8000 characters.
The TEXT data type doesn't support the normal string functions, while VARCHAR(MAX) does - your statement would work just fine, if you'd be using just VARCHAR types.
The + (String Concatenation) does not work on SQL Server for the image, ntext, or text data types.
In fact, image, ntext, and text are all deprecated.
ntext, text, and image data types will
be removed in a future version of
MicrosoftSQL Server. Avoid using these
data types in new development work,
and plan to modify applications that
currently use them. Use nvarchar(max),
varchar(max), and varbinary(max)
instead.
That said if you are using an older version of SQL Server than you want to use UPDATETEXT to perform your concatenation. Which Colin Stasiuk gives a good example of in his blog post String Concatenation on a text column (SQL 2000 vs SQL 2005+).
UPDATE test SET a = CONCAT(a, "more text")
hmm, try doing CAST(' ' AS TEXT) + [myText]
Although, i am not completely sure how this will pan out.
I also suggest against using the Text datatype, use varchar instead.
If that doesn't work, try ' ' + CAST ([myText] AS VARCHAR(255))
To Join two string in SQL Query use function CONCAT(Express1,Express2,...)
Like....
SELECT CODE, CONCAT(Rtrim(FName), " " , TRrim(LName)) as Title FROM MyTable