Get minimum value from columnconcat from three tables + lpad inside. MS SQL - sql-server

I am working in SQL Server Managment Studio 2014.
In the project I am working on I have three tables, each containing 2 columns, one datetime with the exact date (but on time is contained) and the other one - smallint containing time (8:55 is 855 value, while for example 14:45 is 1445).
What I want to do is to get minimum value which is merged from both of those columns from all of those three tables.
What I have figure out by myself until now is:
Use lpad("U_StartTime", 0, '4') to fill values like 855 into 0855 (for exact comparison). However lpad is not recognized at my studio.
lpad is not recognized built in function
Then I can merge both columns like this:
SELECT concat("U_StartDate", ' ', "U_StartTime") FROM "TABLE1".
This is ok until I try make it with lpad.
Then I may take all values to consider like this:
SELECT concat("U_StartDate", ' ', "U_StartTime") FROM "TABLE1"
UNION
SELECT concat("U_StartDate", ' ', "U_StartTime") FROM "TABLE2"
...
And I can take MIN(column) but I do not know how to get MIN from the whole UNION SELECT (of those three tables).
Thank you in advance for any advices on my current sql problems.
edit - image for NikHil:
EDIT:
I have changed the way a bit. Now I am modifying datetime object rather than working on string comparison. As an example for someone I paste part of the code:
select DATEADD(minute, "U_StartTime"%100, DATEADD(hour, "U_StartTime"/100, "U_StartDate")) from "TABLE1"
rather than
select MIN(concat("U_StartDate", ' ', RIGHT('0000' + "U_StartTime", '4'))) from "TABLE1"

You can use RIGHT instead of lpad
SELECT RIGHT('0000' + '855', 4) -- 0855
SELECT RIGHT('0000' + '1445', 4) -- 1445
Query looks like
SELECT MIN(RIGHT('0000' + YourColumn, 4) * 1)
FROM
Tbl

may be you can try this
select data from
(
select concat("U_StartDate", ' ', "U_StartTime")as 'data' from "TABLE1"
UNION
select concat("U_StartDate", ' ', "U_StartTime")as 'data' from "TABLE2"
...
)
where data is not null
order by data asc
LIMIT 1;

Related

Is there a SQL Server collation option that will allow matching different apostrophes?

I'm currently using SQL Server 2016 with SQL_Latin1_General_CP1_CI_AI collation. As expected, queries with the letter e will match values with the letters e, è, é, ê, ë, etc because of the accent insensitive option of the collation. However, queries with a ' (U+0027) do not match values containing a ’ (U+2019). I would like to know if such a collation exists where this case would match, since it's easier to type ' than it is to know that ’ is keystroke Alt-0146.
I'm confident in saying no. The main thing, here, is that the two characters are different (although similar). With accents, e and ê are still both an e (just one has an accent). This enables you (for example) to do searches for things like SELECT * FROM Games WHERE [Name] LIKE 'Pokémon%'; and still have rows containing Pokemon return (because people haven't used the accent :P).
The best thing I could suggest would be to use REPLACE (at least in your WHERE clause) so that both rows are returned. That is, however, likely going to get expensive.
If you know what columns are going to be a problem, you could, therefore, add a PERSISTED Computed Column to that table. Then you could use that column in your WHERE clause, but display the one the original one. Something like:
USE Sandbox;
--Create Sample table and data
CREATE TABLE Sample (String varchar(500));
INSERT INTO Sample
VALUES ('This is a string that does not contain either apostrophe'),
('Where as this string, isn''t without at least one'),
('’I have one of them as well’'),
('’Well, I''m going to use both’');
GO
--First attempt (without the column)
SELECT String
FROM Sample
WHERE String LIKE '%''%'; --Only returns 2 of the rows
GO
--Create a PERSISTED Column
ALTER TABLE Sample ADD StringRplc AS REPLACE(String,'’','''') PERSISTED;
GO
--Second attempt
SELECT String
FROM Sample
WHERE StringRplc LIKE '%''%'; --Returns 3 rows
GO
--Clean up
DROP TABLE Sample;
GO
The other answer is correct. There is no such collation. You can easily verify this with the below.
DECLARE #dynSql NVARCHAR(MAX) =
'SELECT * FROM (' +
(
SELECT SUBSTRING(
(
SELECT ' UNION ALL SELECT ''' + name + ''' AS name, IIF( NCHAR(0x0027) = NCHAR(0x2019) COLLATE ' + name + ', 1,0) AS Equal'
FROM sys.fn_helpcollations()
FOR XML PATH('')
), 12, 0+ 0x7fffffff)
)
+ ') t
ORDER BY Equal, name';
PRINT #dynSql;
EXEC (#dynSql);

How can I append a column in SQL?

I've tried different things in SQL Server 2012 to append the columns. CONCAT merges the columns look like this: catdogparrot whereas I want it be in a list like:
cat
dog
parrot
I've also tried the + in SQL, giving me the same result. I saw '||' as well, but for some reason it says wrong syntax at the second pipe. Is there a way to append a column to a new one? Or would I have to create a new column from the multiple columns? These columns are in the same table. Any suggestions are advice are greatly appreciated, thanks!
I'm not sure what you are trying to do, but you could try to use
CONCAT(' - ', `column1`, ' - ', `column2`, ' - ', ... `column999`)
Eventually this could help you: You can set the separator to any sequence, even to CHAR(13)+CHAR(10), which is a windows line break.
DECLARE #dummyTbl TABLE(animal VARCHAR(10));
INSERT INTO #dummyTbl
VALUES('cat'),('dog'),('parrots');
DECLARE #separator VARCHAR(5)= ' / ';
SELECT STUFF(
(
SELECT #separator + animal
FROM #dummyTbl AS dt
FOR XML PATH(''),TYPE
).value('.','varchar(max)'),1,LEN(#separator),'');

How to produce JSON strings from SQL Server queries via TSQL?

I wanted to know if there is any function or something to convert the SQL select query result to JSON string format?
For example, SQL select query result is,
current target
-----------------
500 1000
1500 2000
JSON result:
[{"current":500,"target":1000},{"current":1500,"target":2000}]
Any ideas will be helpful.
Thanks.
SQL Fiddle
MS SQL Server 2008 Schema Setup:
Query 1:
DECLARE #TABLE TABLE ([current] INT, [target] INT)
INSERT INTO #TABLE VALUES
(500 , 1000),
(1500 , 2000)
SELECT '[' + STUFF((SELECT ',{"current":' + CAST([current] AS VARCHAR(30))
+ ',"target":' + CAST([target] AS VARCHAR(30)) + '}'
FROM #TABLE
FOR XML PATH(''),TYPE).value('.','NVARCHAR(MAX)'),1,1,'') + ']'
Results:
[{"current":500,"target":1000},{"current":1500,"target":2000}]
You don't specify version.
In SQL Server 2016 you will be able to do something like
SELECT [current],
target
FROM YourTable
ORDER BY [current]
FOR JSON AUTO;
More details here or in the official pre release documentation
I use
SELECT
JSON_QUERY(( SELECT
[current],target
FROM YourTable
FOR JSON PATH
))
Works well with minimal effort. I generally convert the output to a List<Dictionary<string,dynamic>> in C#/.Net (if I don't have an existing model).

Generate SQL insert statements of some records in a table

I try to auto generate insert SQL statement from an existing table in SQLServer 2008 but I do not need all record, only a small part of them. --> I thus need to filter the generated inserts. Adding a WHERE clause when generating the insert SQL statements would do the trick but I do not know how to do it.
This article answer to my question partly (SSMS internal generator) :
What is the best way to auto-generate INSERT statements for a SQL Server table?
But it exports all the data of a table. The insert scripts generated are not sorted thus I cannot filter the row I need easily (heavy manual work).
I also tried this stored procedure here (I also had to correct a part of the procedure to make it work with SQLServer 2008 replace char(255) by varchar as explained here)
But it is still not working : I get the following error :
Msg 8169, Level 16, State 2, Line 6
Conversion failed when converting from a character string to uniqueidentifier.
Could you then give me the best way to auto generate SQL Insert in SQL server 2008 from a part of a portion of a table (thus not all the rows of the table) ?
I found a way myself using Excel.
Make needed query including WHERE clause in SSMS
Select all the result
Copy with header
Paste in Excel file here under in 4th row, 1st column
Change in macro output path
Change in cell table name
Launch macro
--> take the file generated and you have a copy of your data ready to be insert again
https://dl.dropboxusercontent.com/u/49776541/GenerateInsert.xlsm
You can use merge syntax to insert data in table based on specific condition
using merge you can also delete and update data in table.you can also do
multiple operation in single sql statement.
There is an easier way to do this, other than going through all the fuss of an excel sheet.
This will return all the data in a table (much like the GUI version) where you right click on the database and select “Tasks” then select “Generate scripts”.
However, unlike the GUI version or the “export to excel” version, with this line of code, you can specify a filter in a “WHERE” clause to return only items for a particular day, or range of days, or any other filter that would normally be used in a “WHERE” clause.
In the code below, I am using 2 simple tables. One is populated with data, the other is not. I want to transfer some or all of the data from table2 to table3. Again, I can filter by date or parts of other columns. (for example… WHERE colB LIKE 'ging%';
This will generate a string of “INSERT” statements preformed in SQL query ready to run.
Note, before running this, switch your output display in SQL server from “Grid” to “Text”.
SELECT 'INSERT', + 'INTO', + 'TestTable3', + '(', + 'colA', + ',', + 'colB', + ',', + 'colDate', + ')', + 'values', + '(', + '''', + CAST(colA AS VARCHAR(10)), + '''', + ',', + '''', + CAST(colB AS VARCHAR(10)), + '''', + ',', + '''', + CAST(DATEADD(DAY, -1, GETDATE()) AS DATE) AS 'colDate', + '''', + ')', + ';'
FROM TestTable2
WHERE colDate LIKE '2018-10-14';
GO
Here is a snippet of what this will return.
Simply copy/paste the results into a new query and run it.
Too easy.

Join query with user provided data-T-sql

I have a requriment where user will provide many Ids(in Hundres/thousands) in a Text area in vb.net app, I need to use these IDs in T-Sql(Sql Server) to get the data. I dont want to save these Ids in any database table. Just want to pass using a paramater (type of varchar(max)) and use in the procedure.
actually, only read access is permitted for the vb application users.It is Sql-2005 database.Id field is atleaset 12 to 15 characters length.The user will copy/paste data from other source may be CSV or Excel file.
any idea how can i achive this.
any help is appreciated.
Thanks
If you do not want to use Table Valued Parameters, as suggested elsewhere, and you don't want to store the ID's in a temporary table, you can do the following.
Assuming your ID's are integer values, that are separated by commas, in the parameter string, you can use the LIKE operator in your SQL-statement's WHERE filter:
Say you have a parameter, #IDs of type varchar(max). You want to get only those records from MyTable where the ID-column contains a value that has been typed into the #IDs-parameter. Then your query should look something like this:
SELECT * FROM MyTable
WHERE ',' + #IDs + ',' LIKE '%,' + CAST(ID AS varchar) + ',%'
Notice how I prepend and append an extra comma to the #IDs parameter. This is to ensure that the LIKE operator will still work as expected for the first and last ID in the string. Make sure to take the nescessary precautions against SQL injection, for example by validating that users are only allowed to input integer digits and commas.
Try using CHARINDEX:
DECLARE #selectedIDs varchar(max) = '1,2,3'
Set #selectedIDs = ',' + #selectedIds + ',' --string should always start and end with ','
SELECT * FROM YourTable
WHERE CHARINDEX(',' + CAST(IDColumn as VARCHAR(10)) + ',', #selectedIds) > 0

Resources