Case used in integer values - sql-server-2008

LocationID LocationName
50 Sharjah
51 Qatar
55 Rigga
6 Dubai Mall
I need to make sql query that takes locationId as parameter,
if locationId is passed 0 then I want to show all this records otherwise show as per locationId passed.
I tried case statement but not succeeded.

Try this : Here #Parm will be passing value to your script
SELECT *
FROM TableName
WHERE (#Parm = 0 OR LocationID = #Parm)

DECLARE #locationId INT;
SELECT LocationID, LocationName
FROM yourTable
WHERE #locationId = 0 OR LocationID = #locationId

I have created a stored proc for you.
CREATE TABLE #LOCATIONS
(
LocationID INT
,LocationName VARCHAR(100)
)
INSERT INTO #LOCATIONS VALUES(
50,'Sharjah')
,(51,'Qatar')
,(55,'Rigga')
,(6,'Dubai Mall')
SELECT * FROM #LOCATIONS
GO
CREATE PROC LOC ( #LOC_ID INT )
AS
BEGIN
IF(#LOC_ID = 0)
SELECT * FROM #LOCATIONS
ELSE
SELECT * FROM #LOCATIONS WHERE LocationID = #LOC_ID
END
GO
EXEC LOC 0 -- Try Executing the stored proc like this
EXEC LOC 55 -- Try Executing the stored proc like this

Related

Ignore error rows when inserting into an table

Says I have this t-sql command :
Insert into x(a,b) select a,b from y
While x contains 10 records, two of them will generate errors when inserted into y, like string should be truncated or numeric overflow. Now what I want is when the command is executed, only 8 records will be inserted into y, meaning that all error records will be ignored.
Is this possible?
cannot understand, why such requirement is there. solution is there, but still not satisfied with requirement or say not able to digest such scenario.
you can loop through each record one by one and if no error then insert.
try this
Set Nocount On;
Declare #Id Int
,#Total Int
,#Loop Int
,#a Varchar(5)
,#b Numeric(3,1)
If Object_Id('tempdb.dbo.#x') Is Not Null
Begin
Drop Table #x;
End
If Object_Id('tempdb.dbo.#y') Is Not Null
Begin
Drop Table #y;
End
Create Table #x
(
Id Int Identity(1,1) Primary Key
,a Varchar(5)
,b Numeric(3,1)
)
Create Table #y
(
Id Int Identity(1,1) Primary Key
,a Varchar(10)
,b Numeric(5,2)
)
Insert Into #y(a,b)
Values
('abcdef',200)
,('abc',12)
,('abfdef',260)
,('34c',16)
,('abwe',18)
,('asdc',29)
,('3fgc',17)
,('a45we',88)
,('a3d7',49)
,('a367',48)
Select #Total = Count(*)
,#Id = 0
,#Loop = 0
From #y With (Nolock)
While (#Loop < #Total)
Begin
Select Top 1
#Id = y.Id
,#a = Substring(y.a,0,5)
,#b = Cast(y.b As Numeric(3,1))
From #y As y With (Nolock)
Where y.Id > #Id
Order By y.Id Asc
If ##Error <> 0 Goto NextLevel
Insert Into #x
Select #a
,#b
Goto NextLevel
NextLevel:
Select #Loop = #Loop + 1
End
Select *
From #x With (Nolock)

A sql function that returns true/false with some data calculations problems

I need to create a function in sql that returns 0 or 1 if the "totalOrderSum" is lower than 1000 or higher. The parameters that are going in are #artNr, #orderNr and #amount. The problem is that I have to find the #artNr price from another table and get that price * #amount and after that I have to get the total TotalAmount from one more table and see if (TotalAmount + (#price * #amount) < 1000).
I have some sql code below and I think you know what i want to do with the code.
Many thanks in advance.
CREATE FUNCTION Lab2_spAddOrderLine(#artNr INT,#orderNr INT,#amount) RETURNS BIT
WITH SCHEMABINDING
AS BEGIN
DECLERE #result BIT, #price INT,#totalPrice
IF(
SELECT Price
FROM Lab2_Article
WHERE ArtNr=#artNr AS #price
AND WHERE (
SELECT TotalAmount
FROM Lab2_CostomOrder
WHERE OrderNr = #orderNr AS #totalPrice
AND WHERE ((#totalPrice +(#price * #amount)) < 1000
)
)
SET #result = 1
ELSE
SET #result = 0
RETURN #result
END
DELIMITER //
CREATE PROCEDURE lab2_addOrderLineProcedure
(
IN articleNr INT,
IN orderNr INT,
IN amount INT,
OUT result BIT
)
BEGIN
DECLARE price INT;
DECLARE totalPrice INT;
SET price = (SELECT Price FROM Lab2_Article WHERE ArtNr = articleNr);
SET totalPrice = ((SELECT TotalPrice FROM Lab2_CostomOrder WHERE orderNr = orderNr) + (price * amount));
IF totalPrice < 1000 THEN
INSERT INTO Lab2_OrderLine VALUES (articleNr, orderNr, amount);
SET result = 1;
ELSE
SET result = 0;
END IF;
END //
DELIMITER ;
There are so many errors in your code. Try the following:-
CREATE FUNCTION Lab2_spAddOrderLine(`artNr` INT, `orderNr` INT, `amount` int)
RETURNS BIT
BEGIN
DECLARE `result` BIT, `price` INT, `totalPrice` INT
IF(
SELECT Price
FROM Lab2_Article
WHERE ArtNr=`artNr` AS #price
AND (
SELECT TotalAmount
FROM Lab2_CostomOrder
WHERE OrderNr = `orderNr` AS `totalPrice`
AND ((`totalPrice` +(`price` * `amount`)) < 1000
)
)
SET `result` = 1
ELSE
SET `result` = 0
RETURN `result`
END;

How to split string in sql server and put it in a table

My input is like
(abcd#123, xyz#324, def#567)
I want an output
col1 Col2
abcd 123
xyz 324
def 567
and so on
Column 1 should have abcd and xyz, and column 2 should have 123 and 324 both in different rows and so on. and the String can be of any size.
Thank you
Try this
SELECT LEFT('abcd#123', CHARINDEX('#', 'abcd#123')-1),
RIGHT('abcd#123', CHARINDEX('#', 'abcd#123')-1)
You will need to use CHARINDEX() and SUBSTRING() functions to split your input values.
your actual problem is turning a complex String into a table i gues.
That for i found help with a procedure about 1 year ago, that does exactly that:
CREATE FUNCTION [dbo].[fnSplitString] (
#myString varchar(500),
#deliminator varchar(10))
RETURNS
#ReturnTable TABLE (
[id] [int] IDENTITY(1,1) NOT NULL,
[part] [varchar](50) NULL
)
AS
BEGIN
Declare #iSpaces int
Declare #part varchar(50)
Select #iSpaces = charindex(#deliminator,#myString,0)
While #iSpaces > 0
BEGIN
Select #part = substring(#myString,0,charindex(#deliminator,#myString,0))
Insert Into #ReturnTable(part)
Select #part
Select #myString = substring(#mystring,charindex(#deliminator,#myString,0)+ len(#deliminator),len(#myString) - charindex(' ',#myString,0))
Select #iSpaces = charindex(#deliminator,#myString,0)
END
If len(#myString) > 0
Insert Into #ReturnTable
Select #myString
RETURN
END
Create this procedure and you can do:
DECLARE #TestString varchar(50)
SET #TestString = 'abcd#123,xyz#324,def#567'
Select * from dbo.fnSplitString(#TestString, ',')
Result:
id| part
1 | abcd#123
2 | xyz#324
3 | def#567
this part you can combine with Leonardos answer:
SELECT
LEFT(part, CHARINDEX('#', part)-1) As Col1,
RIGHT(part, LEN(part) - CHARINDEX('#', part)) As Col2
from dbo.fnSplitString(#TestString, ',')
to get your problem solved.
(little note: the function has little issues with whitespaces, so please try to avoid them there)

Need a qry to join a comma separated column with another table with its Id in it to find the code

I have a table with
Table name TB1
mpeFromWHId mpeToStoreList
8 16,18,24
and Table tb2 are the codes of the comma separated storeid
nlid nlcode
16 ncl
18 mcl
24 dcl
I need a query that will result in
col1 Col2
8 ncl,mcl,dcl
First you need a function to parse comma delimited string into table, you can use this (found [here])1:
CREATE FUNCTION [dbo].Split1(#input AS Varchar(4000) )
RETURNS
#Result TABLE(Value BIGINT)
AS
BEGIN
DECLARE #str VARCHAR(20)
DECLARE #ind Int
IF(#input is not null)
BEGIN
SET #ind = CharIndex(',',#input)
WHILE #ind > 0
BEGIN
SET #str = SUBSTRING(#input,1,#ind-1)
SET #input = SUBSTRING(#input,#ind+1,LEN(#input)-#ind)
INSERT INTO #Result values (#str)
SET #ind = CharIndex(',',#input)
END
SET #str = #input
INSERT INTO #Result values (#str)
END
RETURN
END
Then you can use something like this (but there are many more options off course):
declare #searchId int
set #searchId = 8
declare #tb1 table (mpeFromWHId int, mpeToStoreList varchar(100))
insert into #tb1
select 8, '16,18,24'
declare #tb2 table (nlid int, nlcode varchar(30))
insert into #tb2
select 16, 'ncl' union
select 18, 'mcl' union
select 24, 'dcl'
select stuff((
select ',' + nlcode
from #tb2
where nlid in (
select Value
from dbo.Split1((select mpeToStoreList from #tb1 where mpeFromWHId = #searchId))
)
order by nlcode
for xml path(''), type
).value('(./text())[1]','varchar(max)'), 1, 2, '')
If you don't want to create a user function, you can do like this:
;with TB1(mpeFromWHId, mpeToStoreList) AS (
select 8,'16,18,24'
)
SELECT t.mpeFromWHId,n.ID FROM (
select *,convert(XML,'<n>'+replace(mpeToStoreList,',','</n><n>')+'</n>') as x from tb1
) AS t
cross apply(select s.b.value('.','INT') as ID from t.x.nodes('n') s(b)) n
mpeFromWHId ID
8 16
8 18
8 24

sql return data from select statement and insert to table variable at the same time

declare #RelevantMachines Table (MachineId int)
Select MachineId, ClusterId, MachineGuid, MachineName, RegisteredDate, MachineDetail, LastServiceCall, MachineType as MachineTypeId, ProductSetId
From PatchHub.Machine
Where ClusterId = #ClusterId
I would like to be able to return the select statement as a result set whilst at the same time populating the table variable with all of the returned rows MachineId values, this is in sql server 2008. How could you achieve this without running the select statement twice?
I don't believe you can do it in a single SELECT, I think the next best thing would be something like this:
declare #result table (
MachineId int,
ClusterId int,
MachineGuid guid,
MachineName varchar(100),
RegisteredDate datetime,
MachineDetail varchar(1000),
LastServiceCall int,
MachineType int,
ProductSetId int)
Select MachineId, ClusterId, MachineGuid, MachineName, RegisteredDate, MachineDetail, LastServiceCall, MachineType as MachineTypeId, ProductSetId
into #result
From PatchHub.Machine
Where ClusterId = #ClusterId
select * from #result
/* use #result table */