Convert number to string (number in string or null in string) - sql-server-2005

In SQL Server, what is the shortest way to convert a number to string (number in string or null in string):
Example:
number 1 ---> output '1'
number null --> output 'null'

Use CAST and CONVERT (Transact-SQL).
SQL Fiddle
MS SQL Server 2012 Schema Setup:
create table T
(
Number int
);
insert into T values(1);
insert into T values(null);
Query 1:
select cast(Number as varchar(11))
from T;
Results:
| COLUMN_0 |
|----------|
| 1 |
| (null) |
Or isnull(cast(Number as varchar(11)), 'null') if you are looking for the string value null.
Not sure what you man by shortest and why that is important but this is a bit shorter isnull(left(Number, 11), 'null').

Related

Query to combine value of another column value in insert command of same table

I'm really sorry if you don't understand my question, my english is not good .
kindly correct it if can
I create a table called 'Class'
create table class(
candidate_id int identity,
candidate_name varchar(50),
candidate_course varchar(15) default 'SQL Server');
I just want to insert only candidate_name column
Insert into class(Candidate_name)
values('User');
If I execute this command i'll get
Candidate_id
Candidate_name
Candidate_course
1
user
SQL Server
As, identity column will generate no.s so is it possible combine both with candidate_name while inserting .
Just like other languages Print("Hello world "+S) where s='Stack' output would be
Hello world Stack
Expecting output like this
Candidate_id
Candidate_name
Candidate_course
1
user1
SQL Server
2
user2
SQL Server
3
user3
SQL Server
nth
user nth
SQL Server
kindly help . Hope i'm clear
You can concatenate those 2 values simply using '+'.
Also, we need to convert the candidate_id to varchar, since it is integer.
Query
select candidate_id,
Candiate_name + cast(candidate_id as varchar(10)) as candidate_name,
Candidate_course
From class;
It is not possible to concatenate an identity with a user defined value provided in a raw insert statement. That being said there are a couple of things that you can do.
Define the table with a generated column.
You can actually define a column in your table that is generated from other columns.
create table class(
candidate_id int identity,
candidate_name varchar(50),
candidate_course varchar(15) default 'SQL Server',
candidate_name_id AS CONCAT(candidate_name, '_', candidate_id)
);
Insert into class(Candidate_name)
VALUES
('User'),
('User'),
('User');
SELECT *
FROM dbo.class AS c
This produces the following table.
candidate_id
candidate_name
candidate_course
candidate_name_id
1
User
SQL Server
User_1
2
User
SQL Server
User_2
3
User
SQL Server
User_3
For further reference on 'Computed Columns'
https://learn.microsoft.com/en-us/sql/relational-databases/tables/specify-computed-columns-in-a-table?view=sql-server-ver16
Define The Table With A Sequence
Instead of using an identity you can use a sequence which gives you a lot more flexibility. You can generate the next value for the sequence and use it in your insert statements. I actually recommend this since you can generate the sequence before hand and use it in other parts of your code.
CREATE SEQUENCE SQ_class INCREMENT BY 1 START WITH 1 AS INT;
create table class(
candidate_id int DEFAULT NEXT VALUE FOR SQ_class,
candidate_name varchar(50),
candidate_course varchar(15) default 'SQL Server'
);
Insert into class(candidate_id, Candidate_name)
VALUES
(NEXT VALUE FOR SQ_class, CONCAT('User', '_', NEXT VALUE FOR SQ_class)),
(NEXT VALUE FOR SQ_class, CONCAT('User', '_', NEXT VALUE FOR SQ_class)),
(NEXT VALUE FOR SQ_class, CONCAT('User', '_', NEXT VALUE FOR SQ_class));
SELECT *
FROM dbo.class AS c
Which gives you the following result
candidate_id
candidate_name
candidate_course
1
User_1
SQL Server
2
User_2
SQL Server
3
User_3
SQL Server
in the same column you can achieve that, and as the other answer shows you can generate it on every sele as it is redundat, to have another column.
But you can make a generated column
MS SQL Server 2017 Schema Setup:
create table class(
candidate_id int identity,
candidate_name varchar(50),
fnew_candidate AS (candidate_name + cast(candidate_id as varchar(10))) PERSISTED,
candidate_course varchar(15) default 'SQL Server');
Insert into class(Candidate_name)
values('User');
SQL Fiddle
Query 1:
SELECT * FROM class
Results:
| candidate_id | candidate_name | fnew_candidate | candidate_course |
|--------------|----------------|----------------|------------------|
| 1 | User | User1 | SQL Server |
You may use a Trigger to update the inserted candidate_name automatically as the following:
CREATE TRIGGER ClassInsert ON Class
FOR INSERT AS
Begin
Update Class Set candidate_name = (candidate_name + Cast(candidate_id as nvarchar(5)))
Where candidate_id = (Select Max(candidate_id) From Class);
End
See a demo from db<>fiddle.

Query on how to replace numerical data from a string/column

I have values in my column as below. Can anyone help me with how to replace any numeric data present in a column or string to blank using SQL Server query?
Below is the column data. How do I replace the numbers to blank and display only underscores.
You could approach this by counting the number of underscores, and then generating a string containing this number of underscores:
SELECT Column1, REPLICATE('_', LEN(Column1) - LEN(REPLACE(Column1, '_', '')))
FROM yourTable;
Demo
Here is a more generic solution. It will handle not just the underscore chars. It will work starting from SQL Server 2017 onwards.
As #Squirrel correctly mentioned, the TRANSLATE() function is very handy for such cases.
SQL
-- DDL and sample data population, start
DECLARE #tbl TABLE (ID INT IDENTITY PRIMARY KEY, col VARCHAR(256));
INSERT INTO #tbl (col) VALUES
('2413347_6752318'),
('7263_872_767'),
('123Code456');
-- DDL and sample data population, end
SELECT col AS [Before]
, REPLACE(TRANSLATE(col, '0123456789', SPACE(10)), SPACE(1), '') AS [After]
FROM #tbl;
Output
+-----------------+-------+
| Before | After |
+-----------------+-------+
| 2413347_6752318 | _ |
| 7263_872_767 | __ |
| 123Code456 | Code |
+-----------------+-------+

Is using OPENXML() the best way to transform data in an XML Column to Rows and Columns?

I have a SQL Server table with a column of type XML. The XML data represents multiple allowable selections for a given field. An example of the XML data is as follows.
<Values>
<Value>Valid Value 1</Value>
<Value>Valid Value 2</Value>
<Value>Valid Value 3</Value>
<Value>Valid Value 4</Value>
<Value>Valid Value 5</Value>
<Value>Valid Value 6</Value>
...
</Values>
I am using the following code to extract the data from the XML column and transforming it into rows that can be inserted into a new table.
DECLARE #XmlStuff VARCHAR(4000);
DECLARE #iXmlStuff int;
SELECT #XmlStuff = CAST(C.ValidValues AS VARCHAR(4000))
FROM dbo.ColumnValidations C
WHERE C.[ColumnName] = 'Something';
EXEC sp_xml_preparedocument #iXmlStuff OUTPUT, #XmlStuff;
SELECT *
FROM OPENXML(#iXmlStuff, '/Values/Value', 2)
WITH ([Value] VARCHAR(100) '.');
EXEC sp_xml_removedocument #iXmlStuff;
This code is correctly returning the following
Value
----------------
Valid Value 1
Valid Value 2
Valid Value 3
Valid Value 4
Valid Value 5
Valid Value 6
...
Is this the best way of doing this?
What I have here, I think, will need to be in a stored procedure. Ideally I am looking for a way of doing this where I don't have to worry about losing data because of a buffer overflow due to an unforeseen quantity of data contained in the xml column.
OPENXML(), and its companions sp_xml_preparedocument/sp_xml_removedocument is a proprietary Microsoft API. It is kept just for backward
compatibility with the obsolete SQL Server 2000. SQL Server 2005 onwards supports w3c's XQuery 1.0, XPath 2.0, and XSD 1.0.
SQL
-- DDL and sample data population, start
DECLARE #tbl Table (ID INT IDENTITY PRIMARY KEY, xmldata XML);
INSERT INTO #tbl (xmldata) VALUES
(N'<Values>
<Value>Valid Value 1</Value>
<Value>Valid Value 2</Value>
<Value>Valid Value 3</Value>
<Value>Valid Value 4</Value>
<Value>Valid Value 5</Value>
<Value>Valid Value 6</Value>
</Values>');
-- DDL and sample data population, end
SELECT ID
, c.value('.','VARCHAR(100)') AS Result
FROM #tbl CROSS APPLY xmldata.nodes('/Values/Value/text()') AS t(c);
Output
+----+---------------+
| ID | Result |
+----+---------------+
| 1 | Valid Value 1 |
| 1 | Valid Value 2 |
| 1 | Valid Value 3 |
| 1 | Valid Value 4 |
| 1 | Valid Value 5 |
| 1 | Valid Value 6 |
+----+---------------+

SQL server insert encoding

Using SQL Server 2012 Management studio,
running the following command insert the data but modify/convert the "," to another char who look like a comma but is not (char code 8128):
INSERT INTO [dbo].[MyTable] VALUES(3,'City','Qu,bec')
I tried the Prefix N but it didnt worked:
INSERT INTO [dbo].[MyTable] VALUES(3,'City',N'Qu,bec')
However, if i use the "Edit" mode of Management studio, the good value is inserted.
The data type of the column is nvarchar(100)
I think it has something to do about Encoding but I cant find how to fix it. In my C# project, I use LinqToSql to extract the data and I end with the bad char (char code 8128) if the data was inserted with the command instead of the "Edit" mode.
I would appreciate a fix and a short explanation. Thx
If you want to insert these values from code, then you would use the N prefix, and use the actual unicode character like so:
create table mytable (id int, type varchar(16), name nvarchar(64))
insert into mytable values (3,'City',N'Québec')
select * from mytable
rextester demo: http://rextester.com/JUBZS75211
returns:
+----+------+--------+
| id | type | name |
+----+------+--------+
| 3 | City | Québec |
+----+------+--------+

Insert a empty string on SQL Server with BULK INSERT

Example table contains the fields Id (the Identity of the table, an integer); Name (a simple attribute that allows null values, it's a string)
I'm trying a CSV that contains this:
1,
1,""
1,''
None of them gives me a empty string as the result of the bulk insertion. I'm using SQL Server 2012.
What can I do?
As far as I know, bulk insert can't insert empty string, it can either keep null value or use default value with keepnulls option or without keepnulls option. For your 3 sample records, after insert database, it should be like:
| id | name
| 1 | NULL
| 1 | ""
| 1 | ''
The reason is, the bulk insert will treat your first row, second column value as null; for other 2 rows, will take the second column value as not null, and take it as it is. Instead of let Bulk Insert to insert empty string value for you, you can let you table column having default value as empty string.
Example as following:
CREATE TABLE BulkInsertTest (id int, name varchar(10) DEFAULT '')
Bulk Insert same CSV file into table
BULK INSERT Adventure.dbo.BulkInsertTest
FROM '....\test.csv'
WITH
(
FIELDTERMINATOR ='\,',
ROWTERMINATOR ='\n'
)
SELECT * FROM BulkInsertTest
The result will be like following: (The first row in your CSV will get an empty string)
| id | name
| 1 |
| 1 | ""
| 1 | ''
Please bear in mind that the specified DEFAULT value will only get inserted if you are not using the option KEEPNULLS.
Using the same example as above, if you add the option KEEPNULLS to the BULK INSERT, i.e.:
BULK INSERT BulkInsertTest
FROM '....\test.csv'
WITH
(
FIELDTERMINATOR ='\,',
ROWTERMINATOR ='\n',
KEEPNULLS
)
will result in the default column value being ignored and NULLs being inserted fro empty strings, i.e:
SELECT * FROM BulkInsertTest
will now give you:
id name
1 NULL
1 ""
1 ''
There does not seem to be a good reason to add KEEPNULLS this in your example, but I came across a similar problem just now, where KEEPNULLS was required in the BULK INSERT.
My solution was to define make the column [name] in the staging table BulkInsertTest NOT NULL but remember that the DEFAULT column value gets ignored and an empty string gets inserted instead.
See more here : Keep Nulls or UseDefault Values During Bulk Import (SQL Server)