How to Show a particular row first from a select query - sql-server

I have a query results like below
name id
a 2
b 3
c 7
h 9
i 1
i need to show the results like below
Expected Result
name id
c 7
a 2
b 3
h 9
i 1
The id field is Primarykey so based on that i want to show this
so far i tried with order by but it only give the option to order like decenting or acenting.
Please help me to do this
I had done something like below
create procedure proc1
#id int;
begin
select name,id from tablname order by id
end
I had also tried like but it also fails . Please help me to solve this

Try this:
CREATE PROCEDURE proc1 (#id int)
AS
SELECT name,id
FROM tablname
ORDER BY CASE WHEN id=#id THEN 0 ELSE id END
Note: This will work assuming the values of your id columns are always greater then 0.

I tried this and it gives exactly what is your required output.
declare #name varchar(10)
set #name = 'c'
create table #temp (id int ,name varchar(10))
insert into #temp(id,name) values(1,'i')
insert into #temp(id,name) values(2,'a')
insert into #temp(id,name) values(3,'b')
insert into #temp(id,name) values(7,'c')
insert into #temp(id,name) values(9,'h')
Select name,id from #temp ORDER BY CASE WHEN name=#name THEN '' ELSE name END
Drop table #temp

Related

How to pass multiple input id into a stored procedure and get the ids that have all input ids?

My goal is that when the user chooses the product, the application will export the supplier that provides both products. However, if I use a stored procedure, the input must be a fixed value so I can't put a listId like C#.
So, how can I just put a list of Id into the store and I have produced supplier business id of the added productId. See my table below and InventoryOfSentoId is ProductId:
If input is 1 then output is supplierid 1 and 3
If input is 2, 3 then output is supplierid 3
If you are using SQL Server 2014, it is easy to create your own split function. The one I use is the following (but you can google for others that are more efficient, particularly if your list is long):
create FUNCTION [dbo].[fnSplit](
#sDelimiter VARCHAR(5) -- delimiter that separates items
, #sInputList VARCHAR(max) -- List of delimited items
) RETURNS #List TABLE (item VARCHAR(max))
BEGIN
DECLARE #sItem VARCHAR(max)
WHILE CHARINDEX(#sDelimiter,#sInputList,0) <> 0
BEGIN
SELECT
#sItem=RTRIM(LTRIM(SUBSTRING(#sInputList,1,CHARINDEX(#sDelimiter,#sInputList,0)-1))),
#sInputList=RTRIM(LTRIM(SUBSTRING(#sInputList,CHARINDEX(#sDelimiter,#sInputList,0)+LEN(#sDelimiter),LEN(#sInputList))))
IF LEN(#sItem) > 0
INSERT INTO #List SELECT #sItem
END
IF LEN(#sInputList) > 0
INSERT INTO #List SELECT #sInputList -- Put the last item in
RETURN
END
You will then be able to achieve what you want with:
declare #demo table (SupplierID int, InventoryOfSentoID int)
declare #list varchar(10) = '2,3'
declare #ids table (SentoID int)
declare #cnt int
INSERT INTO #demo VALUES (1,1),(1,2),(2,5),(3,3),(3,2),(3,1)
INSERT INTO #ids
SELECT * FROM dbo.fnSplit(',',#list)
SELECT #cnt = COUNT(*) FROM #ids
SELECT SupplierID FROM #demo d
INNER JOIN #ids i
ON i.SentoID = d.InventoryOfSentoID
GROUP BY SupplierID
HAVING COUNT(*) = #cnt
By way of explanation, note the use of the HAVING restriction. This is to ensure that only those suppliers who supply all the elements in the list are returned. If you did not have this restriction, the resultset would include supplierid 1, which from your question I presumed you wanted to exclude.

How to find other than current value in SQL Server?

In SQL Server, how can I get data from a column other than specified data.
For example, I have a column with data "MySQL,Server,Database" in single row.
Now I want to find if there is any other value than MySQL in that column.
I tried by using Not Like but didn't succeed.
For example TableA :
id | Code
---+---------------------------
1 | mysql,sqlserver,database
2 | mysql
3 | sqlserver,database
4 | mysql,mysql
Here, I want to find if the column has data other than "mysql" or not, like id:1 has data other than "mysql" but id:2 have "mysql" but not other than "mysql".
Finally if I want to return the null or blank value if there no any data other than "mysql".
Code I used so far :
select code from tableA where code not like '%mysql%'
It helps if you can provide some data and some code. This works (as far as I understand the question):
CREATE TABLE #x (object_type varchar(50))
INSERT #x (object_type) VALUES ('MySQL'), ('Server'), ('Database')
SELECT * FROM #x WHERE object_type <> 'MySQL'
Base on the updated question, I think you're looking for:
CREATE TABLE #x (id int identity(1, 1), code varchar(50))
INSERT #x (code) VALUES ('mysql,sqlserver,database'), ('mysql'), ('sqlserver,database'), ('mysql,mysql')
SELECT *
FROM #x
WHERE id IN (
SELECT id
FROM #x
CROSS APPLY string_split(code, ',')
WHERE value <> 'mysql'
)
However, as #Eric Brandt asked above, it's not clear whether you want to select row id = 4.
Note STRING_SPLIT is only available for SQL Server 2016 or later. if you are using a earlier version, do a search, there are lots of similar implementation
declare #table table
(
id int identity,
Code varchar(30)
)
insert into #table select 'mysql,sqlserver,database'
insert into #table select 'mysql'
insert into #table select 'sqlserver,database'
insert into #table select 'mysql,mysql'
insert into #table select ''
insert into #table select NULL
select *
from #table t
where t.Code is null
or exists
(
select *
from string_split(t.Code, ',')
where value <> 'mysql'
)
/* RESULT
1 mysql,sqlserver,database
3 sqlserver,database
5
6 NULL
*/

Second counter in SQL Server table

I need to have a table like this:
CLIENT_ID ID CONTENT
--------------------
1 1 abc
1 2 abc
1 3 abc
2 1 abc
2 2 abc
2 3 abc
client_id and id are the table's pk. on the application side, only client client_id and content are known, so I thought to have an after insert trigger that updates the id column as needed, but I'm having troubles. any help? Thanks.
My first attempt was:
CREATE TRIGGER test
ON [dbo].[table]
AFTER INSERT
AS
BEGIN
DECLARE #client_id INT;
DECLARE #id INT;
SELECT #client_id = client_id
FROM inserted;
SELECT #id = ISNULL(MAX(clifor_id), 0) + 1
FROM table
WHERE client_id = #client_id
UPDATE [dbo].[table]
SET [id] = #id
WHERE ?????
END
but don't know how to complete it.
ps: sorry for my English!
#Squirrel pointed you in good direction - instead of trigger is a way to go. S.t. like this one:
CREATE TRIGGER test
ON [dbo].[table]
INSTEAD OF INSERT
AS
BEGIN
UPDATE inserted
SET id = (select 1+max(id) from dbo.table where client_id = inserted.client_id)
INSERT INTO dbo.table
SELECT * FROM inserted --note - you should rewrite this block so it will be with explicit list of columns
END
Note that this will fail if you can insert multiple entries for the same client in one query.

Table variable error: Must declare the scalar variable "#temp"

I am trying to achieve:
declare #TEMP table (ID int, Name varchar(max))
insert into #temp SELECT ID, Name FROM Table
SELECT * FROM #TEMP
WHERE #TEMP.ID = 1 <--- ERROR AT #TEMP.ID
But I'm getting the following error:
Must declare the scalar variable "#temp".
What am I doing wrong?
A table alias cannot start with a #. So, give #Temp another alias (or leave out the two-part naming altogether):
SELECT *
FROM #TEMP t
WHERE t.ID = 1;
Also, a single equals sign is traditionally used in SQL for a comparison.
Either use an Allias in the table like T and use T.ID, or use just the column name.
declare #TEMP table (ID int, Name varchar(max))
insert into #temp SELECT ID, Name FROM Table
SELECT * FROM #TEMP
WHERE ID = 1
There is one another method of temp table
create table #TempTable (
ID int,
name varchar(max)
)
insert into #TempTable (ID,name)
Select ID,Name
from Table
SELECT *
FROM #TempTable
WHERE ID = 1
Make Sure You are selecting the right database.
If you bracket the # you can use it directly
declare #TEMP table (ID int, Name varchar(max))
insert into #temp values (1,'one'), (2,'two')
SELECT * FROM #TEMP
WHERE [#TEMP].[ID] = 1
You should use hash (#) tables, That you actually looking for because variables value will remain till that execution only.
e.g. -
declare #TEMP table (ID int, Name varchar(max))
insert into #temp SELECT ID, Name FROM Table
When above two and below two statements execute separately.
SELECT * FROM #TEMP
WHERE #TEMP.ID = 1
The error will show because the value of variable lost when you execute the batch of query second time.
It definitely gives o/p when you run an entire block of code.
The hash table is the best possible option for storing and retrieving the temporary value. It last long till the parent session is alive.
try the following query:
SELECT ID,
Name
INTO #tempTable
FROM Table
SELECT *
FROM #tempTable
WHERE ID = 1
It doesn't need to declare table.
You could stil use #TEMP if you quote the identifier "#TEMP":
declare #TEMP table (ID int, Name varchar(max));
insert into #temp SELECT 1 AS ID, 'a' Name;
SELECT * FROM #TEMP WHERE "#TEMP".ID = 1 ;
db<>fiddle demo
You've declared #TEMP but in your insert statement used #temp. Case sensitive variable names.
Change #temp to #TEMP

Insert two columns from different tables

I need to write an insert query to insert some rows into a table using data from different tables. I have:
A variable #ID which contains ID of the new inserted row in a table. (1)
A table (2) contains some IDs
A table (3) define the relation between the two above tables.
Now I need to insert for each ID in (2) a new row in the table (3).
So if #ID=2 and IDs = 1, 2, 3, 4, 5, 6, I want to insert the following rows in Table (3):
table1_ID table2_ID
--------- ---------
1 1
1 2
1 3
1 4
1 5
Assuming that the value 6 was not meant to be discarded (if it was, please explain the logic). Also assuming that you just want every row in table 2 inserted into table 2.
INSERT dbo.Table3(table1_ID, table2_ID)
SELECT #ID, ID
FROM dbo.Table2
-- WHERE ID <> 6???
;
If the list of IDs is really a CSV, then:
First create a Split function (several alternatives described here, except they output strings instead of integers), e.g.
CREATE FUNCTION dbo.SplitInts
(
#List VARCHAR(MAX),
#Delimiter VARCHAR(255)
)
RETURNS #t TABLE(Item INT)
AS
BEGIN
INSERT #t(Item) SELECT CONVERT(INT, SUBSTRING(#List, Number,
CHARINDEX(#Delimiter, #List + #Delimiter, Number) - Number))
FROM (SELECT ROW_NUMBER() OVER (ORDER BY [object_id])
FROM sys.all_objects) AS n(Number)
WHERE Number <= CONVERT(INT, LEN(#List))
AND SUBSTRING(#Delimiter + #List, Number, 1) = #Delimiter;
RETURN;
END
GO
Now your stored procedure can simply say:
CREATE PROCEDURE dbo.whatever
#ID INT,
#IDs VARCHAR(MAX)
AS
BEGIN
SET NOCOUNT ON;
INSERT dbo.Table3(table1_ID, table2_ID)
SELECT #ID, Item
FROM dbo.SplitInts(#IDs, ',');
END
GO
However if you are on SQL Server 2008 or above, and this list of comma-separated IDs is coming from your application (e.g. from a DataTable or other set), you could use a Table-Valued Parameter and avoid the need for splitting.
CREATE TYPE dbo.SetOfIntegers
( Number INT );
GO
CREATE PROCEDURE dbo.whatever
#ID INT,
#IDs dbo.SetOfIntegers READONLY
AS
BEGIN
SET NOCOUNT ON;
INSERT dbo.Table3(table1_ID, table2_ID)
SELECT #ID, Item
FROM #IDs;
END
GO
Then you have to change the C# code to pass your DataTable in as SqlDbType.Structured instead of passing your CSV in as a string. More info here:
http://www.sqlperformance.com/2012/08/t-sql-queries/splitting-strings-now-with-less-t-sql

Resources