use variable in select - tsql - sql-server

Hi I have procedure which have parameter(#identFormat)
Example
"GUID"
"LotID|FeatureID"
And now I have Select query which should split this and use as columns.
Moreover result should be back combined.
Example:
Table:
Id LotID FeatureID
2 1 4
3 4 5
4 2 1
and if my #identFormat = "LotID|FeatureID" then it should return
Table:
1|4
4|5
2|1
Actually I have ncharchar #columns 'LotId + "|" + FeatureId'
Is it possible to use this like this:
Select #columns from Table ?
or using dynamic sql
EDIT:
Unfortunately combination of columns can be different. My purpose is send column names to procedure and select this columns from specific table. This is procedure to save data , but if something went wrong I must save this unique combination of columns in second table.

Unfortunatelly, it is not possible. You need to select separately and format the output

Related

Group by based on specific column contains value from list of values

I've one table myTable
ID
Content
1
Hello, this is the test content
2
Hi, test content.
I have one list having different values = ["Hello","Hi","Yes","content"]
Now I have to find occurrence of value in myTable-> content column & resultant table have value & count of that value in myTable-> content column (one row of myTable table can have more than one values & use case-insensitive search).
Output be like:
Value
Count
Hello
1
Hi
1
Yes
0
content
2
I want to make optimal SQL server query.
Assuming you are using SQL Server 2016 or above, you could try converting your list to a table like structure, and perform a left join and count on your table.
For instance :
CREATE TABLE MyTable (
ID INT CONSTRAINT PK_MyTable PRIMARY KEY,
Content NVARCHAR(MAX)
);
INSERT INTO MyTable (ID,CONTENT) VALUES
(1,'Hello, this is the test content'),
(2,'Hi, test content.');
DECLARE #MyList NVARCHAR(MAX)
SET #MyList='["Hello","Hi","Yes","content"]';
SELECT
List.Value,
COUNT(MyTable.Content) Count
FROM OPENJSON(#MyList) List --Convert the list to a json
LEFT JOIN MyTable ON '.' + UPPER(MyTable.Content) + '.' LIKE '%[^a-z]' + UPPER(List.Value) +'[^a-z]%'
GROUP BY List.Value;
You can try it on this fiddle.
Please do note that there is margin for improvement, such as full text index instead of this ugly regular expression clause.
See also :
Search for “whole word match” with SQL Server LIKE pattern

Creating a new column based on another column in SQL Server

Quick question - I want to create another column in SQL Server such as:
Original Table
Type Amount LocNum
Chocolate 15 WC-10202-01
Banana 10 WC-35209-22
Vanilla 5 WC-15815-15
Ideal Table
Type Amount LocNum LocNum2
Chocolate 15 WC-10202-01 WC-10202
Banana 10 WC-35209-22 WC-35209
Vanilla 5 WC-15815-15 WC-15815
If you really need to, you can create a computed column.
ALTER TABLE yourTable ADD LocNum2 AS ( <your calculation here> );
However, unless you need to index on this calculation for some reason, I'd suggest just adding it as a part of your select output.
You can use replace and charindex to do this as below:
select [Type], [Amount], LocNum, LocNum2 = replace(LocNum,right(LocNum, charindex('-',LocNum,charindex('-',LocNum,1))),'')
from yourtable
As simple as that:
ALTER TABLE table_name
ADD column_name column-definition;

How to Split the String and integer in Sql to find the max and put it in SP or functions to call

I have a Retailer code ,It is combination of varchar and Int =>RT003880 like this
I have create a Retailer code as script-wise every day. So i need the last Retailer code i have inserted.
So I have split the Integer and varchar for finding the Max value.
This is the max value by using Query.
select SUBSTRING(Retailer_code,5,9) as RetailerCode
Into #maxfindtable
from dbo.sample
select MAX(RetailerCode) from #maxfindtable
I need to put in in function or Stored Procedure how to do this
Try:
select max(SUBSTRING(RetailerCode,3,len(RetailerCode)-2))
for RT003880 the integer part is starting from position 3,and
len(RetailerCode)-2 isdefine the length of the substring. i.e: all the
character starting from 3rd position
See SUBSTRING for more clearification.
EDIT 2:
try Using Cast
create table #tab (genId varchar(max))
insert into #tab(genId)
values('RT00031'),('RT00013232'),('RT00034'),('RT00084')
select * from #tab
select max(cast(SUBSTRING(genId,3,len(genId)-2) as int)) from #tab
I'd split the RetailerCode into two columns (one CHAR/VARCHAR and one INT/SMALLINT/NUMERIC) to be able to get some performance out of the table. Possibly use a calculated column to concatenate them if requested. I would never query on the calculated column if it was not persisted, however.
Today I have inserted 10000 new records,its choosing wrong max value. Both The codes Written Same Value,Maximum Value is RT0017898,But It shows RT0009999.
After I have Checked a sample data
RetailerId RetailerCode RetailerName
1 RT00031 mBigBazar
2 RT00034 TBazar
3 RT00084 SaravanaStore It shows Correct Value - 00084
When I have insert a new Record it shows wrongly
RetailerId RetailerCode RetailerName
1 RT00031 mBigBazar
2 RT00034 TBazar
3 RT00084 SaravanaStore
4 RT00013232 NewStore
Now it shows 00084 .why it shows wrong?

Convert SQL columns to rows

I would like to split one records columns into multiple rows.
If I have a SQL statement like the following:
SELECT 1,2,3
Result:
1 | 2 | 3
How do I convert that to the following result?
1
2
3
I am currently using MS SQL 2008.
SELECT 1
UNION
SELECT 2
UNION
SELECT 3
To sum up the comments above:
If you want to convert columns into rows, you will need to use the
T-SQL UNPIVOT clause.
If you want to split a single column that contains comma separated
values, you will need to create a Function (example here)

Simple SQL approach to transform columns into rows (SQL Server 2005 or 2008)

On SQL Server, executing the following SQL Statement:
SELECT 1,2,3
will return
(no column name) (no column name) (no column name)
1 2 3
Note that the columns don't have names and the number of columns is not definite (it can have 1 column or it can also have > 100 columns).
My question is - Does anybody know of a simple approach so I can get the following result:
(no column name)
1
2
3
What I'm really trying to do is come up with a SQL similar to the one below. I wish I could execute it as it is but of course we know that the Select 1,2,3 won't work, we have to somehow transform that into a table with the values in each row.
SELECT *
FROM NORTHWIND.DBO.CUSTOMERS
WHERE EMPLOYEEID IN (*Select 1,2,3*); -- *Select 1,2,3 will not work
Currently I'm thinking of creating a user defined function that returns a table by iterating through each column and dynamically creating multiple SQL statements combined by UNION similar to: SELECT 1 Col1 UNION SELECT 2 UNION SELECT 3. I'm not a fan of dynamic SQL and looping procedures in my queries as it can be expensive to process especially for an application with expected usage of 1000+ per minute. Also, there is that concern for SQL Injection Attacks with Dynamic SQL when I start using strings instead of integer values. I'm also trying to avoid temporary tables as it can even be more expensive to process.
Any ideas? Can we use UNPIVOT without the need for looping through the indefinite number of columns and dynamically creating the SQL text to execute it and transform the columnar values into rows? What about Common Table Expressions?
Get rid of the select and just specify a list of values:
SELECT * FROM NORTHWIND.DBO.CUSTOMERS
WHERE EMPLOYEEID IN (1,2,3);

Resources