Using quotes in a variable to construct a string in SQL [duplicate] - sql-server

This question already has answers here:
How do I escape a single quote in SQL Server?
(14 answers)
Closed 1 year ago.
I have a string pulling from XML. It is pulling a single value out of a record. the only part that changes when calling the item is the field name.
for example, the first below pulls the 'resolution' for the item,
the second below pulls the 'name' of the item:
XMLData.value('(ImportFormXml/Resolution)[1]','VARCHAR(50)') AS Resolution
XMLData.value('(ImportFormXml/Name)[1]','VARCHAR(50)') AS Name
I would like to declare a variable and use it as one of the two ways below.
WAY 1 (Preferred)
DECLARE
#Var1 Varchar(50)
SET #Var1 = 'XMLData.value('(ImportFormXml/' [BE ABLE TO INSERT NAME HERE...THIS CAN'T BE ANOTHER VARIABLE]')[1]','VARCHAR(50)')
SELECT
#Var1 INSERT 'Resolution' AS Resolution
, #Var2 INSERT 'Name' AS Name
From TableX
WAY 2
DECLARE
#Var1 Varchar(50)
#Var2 Varchar(50)
SET #Var1 = 'XMLData.value('(ImportFormXml/'
SET #Var2 = ')[1]','VARCHAR(50)')
SELECT
#Var1 + 'Resolution' + #Var2 AS Resolution
, #Var1 + 'Name' + #Var2 AS Name
From TableX

A minimal reproducible example is not provided.
So I am shooting of the hip.
SQL
-- DDL and sample data population, start
DECLARE #tbl TABLE (ID INT IDENTITY PRIMARY KEY, XMLColumn XML);
INSERT INTO #tbl (XMLColumn) VALUES
(N'<ImportFormXml>
<Resolution>Some kind of resolution</Resolution>
<Name>Just a name</Name>
</ImportFormXml>');
-- DDL and sample data population, end
SELECT ID
, c.value('local-name(*[1])','VARCHAR(50)') + ': ' +
c.value('(Resolution/text())[1]','VARCHAR(50)') AS Col1
, c.value('local-name(*[2])','VARCHAR(50)') + ': ' +
c.value('(Name/text())[1]','VARCHAR(50)') AS Col2
FROM #tbl
CROSS APPLY XMLColumn.nodes('/ImportFormXml') AS t(c);
Output
+----+-------------------------------------+-------------------+
| ID | Col1 | Col2 |
+----+-------------------------------------+-------------------+
| 1 | Resolution: Some kind of resolution | Name: Just a name |
+----+-------------------------------------+-------------------+

Related

Concatenate text from multiple rows into a single text string in SQL server? [duplicate]

This question already has answers here:
How to concatenate text from multiple rows into a single text string in SQL Server
(47 answers)
Closed 1 year ago.
I have a table in a SQL-Server database (SQL-Server 2016) with 2 fields:
ConcateCode
ID int,
Random nchar(5)
ID Random
1 A2dd4
2 2f4mR
3 dhu9q
4 0lpms
Now I need a query where I get all the Random-fields concatenated in one field from Start-ID to End-ID, e.g. something like
SELECT ConcateCode FROM Table WHERE ID >= 1 AND ID < 5
and returns A2dd42f4mRdhu9q0lpms.
The problem is that I can't use a StoredProcedure, because my Programming-Language doesn't support Stored-Procedures, but only direct table access or queries.
The question sounds stupid easy, but I try to solve the problem now for a week and get no solution. Hope someone is more intelligent than me.
DECLARE #Result VARCHAR(MAX)
DECLARE #StartID int = 1
, #EndID int = 5
SELECT #Result= COALESCE(#Result, '') + ConcateCode FROM Table
WHERE ID BETWEEN #StartID AND #EndID
SELECT #Result
Try this:
DECLARE #MyTable TABLE (ID int, Random nchar(5))
INSERT INTO #MyTable VALUES
( 1, 'A2dd4')
, ( 2, '2f4mR')
, ( 3, 'dhu9q')
, ( 4, '0lpms')
;
DECLARE #StartID int = 1
, #EndID int = 5
;
DECLARE #String varchar(max) = (SELECT ''+Random FROM #MyTable WHERE ID BETWEEN #StartID AND #EndID FOR XML PATH('') );
SELECT #String;

SQL Server : select merge all values with same keys

I have a table in SQL Server that looks like this:
id: int
key: nvarchar(max)
value: nvarchar(max)
I want to select distinct keys as first column and all values with same key joined with '<br/>' as my second column. The key values are dynamic and is not predefined - and the performance really matters - I don't want to use Linq or any UDF!
id key value
---------------------------------------
1 color red<br/>white<br/>black
4 size 15"
PS: I have searched a lot sorry if it's duplicated, currently running on SQL Server 2014 but I can move to 2019
Please try the following solution. It will work starting from SQL Server 2008 onwards.
SQL
-- DDL and sample data population, start
DECLARE #tbl TABLE (ID INT IDENTITY PRIMARY KEY, [key] NVARCHAR(MAX), [value] NVARCHAR(MAX));
INSERT INTO #tbl ([key], [value]) VALUES
(N'color', N'red'),
(N'color', N'white'),
(N'color', N'black'),
(N'size', N'15"');
-- DDL and sample data population, end
DECLARE #separator CHAR(5) = '<br/>'
, #encoded VARCHAR(20) = '<br/>';
SELECT c.[key]
, STUFF(REPLACE(
(SELECT #separator + CAST([value] AS NVARCHAR(MAX)) AS [text()]
FROM #tbl AS O
WHERE O.[key] = C.[key]
FOR XML PATH('')
), #encoded, #separator)
, 1, LEN(#separator), NULL) AS valueList
FROM #tbl AS c
GROUP BY c.[key];
Output
+-------+-------------------------+
| key | valueList |
+-------+-------------------------+
| color | red<br/>white<br/>black |
| size | 15" |
+-------+-------------------------+

SQL Server Dynamic Pivot Table - Column Name Duplicate

I am attempting to Pivot a table passed in as a UDT.. Column 1 will have duplicate values and Column 2 will have different values (example below). I am hoping for the Column Name to be set as Phone Number and the two Values under the Phone Number column.
DECLARE #query AS NVARCHAR(MAX) = '';
--Temp Table to act as UDT for ease of testing
DECLARE #udt TABLE (DatabaseFieldName nvarchar(50), Value nvarchar(50))
INSERT INTO #udt VALUES('PhoneNumber','01234567890')
INSERT INTO #udt VALUES('PhoneNumber','09876543210')
--Preview of table before Pivot
select * from #udt
CREATE TABLE #temp
(
DatabaseFieldName nvarchar(50),
Value nvarchar(50)
)
INSERT INTO #temp
SELECT DatabaseFieldName, Value
FROM #udt
SELECT #cols = #cols + QUOTENAME(DatabaseFieldName) + ',' FROM (select distinct DatabaseFieldName from #temp) as temp
SELECT #cols = substring(#cols, 0, len(#cols)) -- Trims ',' at the end
SET #query =
'
SELECT * FROM
(
SELECT DatabaseFieldName, Value
FROM #temp
) AS SRC
PIVOT
(
MIN(Value) for DatabaseFieldName in (' + #cols + ')
) AS PivotTable';
execute(#query)
DROP TABLE #temp
Example of current & desired results
Data as it comes in:
DatabaseFieldName | Value
--------------------------------
PhoneNumber | 01234567890
PhoneNumber | 09876543210
Outcome I am hoping to get:
PhoneNumber
------------
01234567890
09876543210
What I am currently getting:
PhoneNumber
------------
01234567890
At the moment the second number is being ignored due to the use of distinct in the select statement, however an error is thrown if distinct is not used.
Are all the values that you want in the pivoted column PhoneNumbers? If so, you can just select the phone numbers themselves with an alias. E.g
SELECT Value As PhoneNumber
FROM (either #UDT or #temp)
WHERE DatabaseFieldName = 'PhoneNumber'
Unless there is a requirement I'm missing here, this would do everything you want it to.
It is not due to DISTINCT, it is because of using MIN(Value) , it gets the first one.
Let's say you had another set of rows
INSERT INTO #udt VALUES('Name','Hello')
INSERT INTO #udt VALUES('Name','Test')
Now the result set of your dynamic SQL will look like this.
Name PhoneNumber
Hello 01234567890
Having said that PIVOT can be used only with aggregate functions, you will get error if MIN is removed. You might have to think of other options for getting desired results such as using case if needed for multiple fields
SELECT CASE WHEN DatabaseFieldName = 'PhoneNumber' THEN Value END AS PhoneNumber,
CASE WHEN DatabaseFieldName = 'Name' THEN Value END AS Name
FROM #udt

Pivot and concatenate values from column in SQL Server

I have table with these columns:
ID | Name | Value
------------------
1 | Test1 | 0
2 | Test2 | 1
3 | Test3 | 0
4 | Test4 | 0
5 | Test5 | 1
And I want to have pivoted and concatenated value column as string
01001
The below code will give the expected result:
SELECT #Result = #Result + CAST(VALUE AS VARCHAR)
FROM #TmpTestingTable
Or you can use the STUFF:
SELECT STUFF(
( SELECT CAST(VALUE AS VARCHAR)
FROM #TmpTestingTable
FOR XML PATH ('')
), 1, 0, '')
For sample, I inserted the columns into the temporary table and execute the code.
CREATE TABLE #TmpTestingTable (ID INT, Name VARCHAR (20), Value INT)
INSERT INTO #TmpTestingTable (ID, Name, Value) VALUES
(1 , 'Test1' , 0),
(2 , 'Test2' , 1),
(3 , 'Test3' , 0),
(4 , 'Test4' , 0),
(5 , 'Test5' , 1)
DECLARE #Result AS VARCHAR (100) = '';
-- using variable approach
SELECT #Result = #Result + CAST(VALUE AS VARCHAR)
FROM #TmpTestingTable
SELECT #Result
-- using STUFF approach
SELECT STUFF(
( SELECT CAST(VALUE AS VARCHAR)
FROM #TmpTestingTable
FOR XML PATH ('')
), 1, 0, '')
DROP TABLE #TmpTestingTable
Use FOR XML to concatinate. It is important that you also include an ORDER BY. Otherwise you have no control of the order of the values and you risk an arbitrary order.
SELECT
(SELECT CAST([VALUE] AS CHAR(1))
FROM yourtable
ORDER BY ID
FOR XML PATH ('')
)
SELECT GROUP_CONCAT(Value SEPARATOR '') FROM Table
EDIT:
Not working on SQL Server. Have a look at Simulating group_concat MySQL function in Microsoft SQL Server 2005? to try to make it work

Assigning select results into variable in stored procedure in mssql?

I have the following select:
SELECT School_Type,COUNT(ID) from Schools where City_ID = 1 group by School_Type
I get results:
10 | 3
20 | 4
30 | 14
I want to put results that are:
type 10 to variable #ElementarySchools
type 20 to variable #HighSchools
type 30 to variable #ProfessionalSchools
and get this result back from the Stored Procedure.
How do I do this ?
something like this? :)
declare #val varchar(max) = ''
select #val = #val + rtrim(foryear) + ' | ' + RTRIM( COUNT(*)) + ',' from mytable
group by ForYear
select #val
Using a table variable like this:
declare #tmp table (School_Type int, School_Count int)
insert into #tmp
SELECT School_Type,COUNT(ID) from Schools where City_ID = 1 group by School_Type
select #ElementarySchools=School_Count from #tmp where School_Type=10
select #HighSchools=School_Count from #tmp where School_Type=20
select #ProfessionalSchools=School_Count from #tmp where School_Type=30

Resources