Set a Value in Verbal using sql - sql-server

I want to set "InOperator" value in a Verbal. This is my select Query.
DECLARE #i nvarchar(Max); set #i = '619, 618, 620, 2162, 2173, 3613, 2090';
select * from tbl_PharmacypurDetail where ItmCode in (CAST(#i as bigint))
Result
Msg 8114, Level 16, State 5, Line 2
Error converting data type nvarchar to bigint.

You can use STRING_SPLIT to splits a string into rows of substrings, based on a specified separator character.
DECLARE #i nvarchar(Max); set #i = '619, 618, 620, 2162, 2173, 3613, 2090';
select * from tbl_PharmacypurDetail where ItmCode in (SELECT value FROM STRING_SPLIT(#i, ','))

You can use split function :
select tp.*
from tbl_PharmacypurDetail tp cross apply
dbo.splitfn(#i, ',') as t(val)
where t.val = tp.itemcode;
If you are working with SQL Server 2016 or higher then you can use STRING_SPLIT.

You can use something like this instead in case your server doesn't support STRING_SPLIT:
DECLARE #i nvarchar(Max);
SET #i = '619, 618, 620, 2162, 2173, 3613, 2090';
SELECT *
FROM tbl_PharmacypurDetail
WHERE CHARINDEX(',' + CONVERT(NVARCHAR(MAX), ItmCode) + ',', ',' + REPLACE(#i, ' ', '') + ',') > 0

Related

Problem passing a datetime variable into a dynamic SQL query

I'm trying to execute a dynamic SQL query, but I'm getting an error Msg 105, Level 15, State 1, Line 1
Unclosed quotation mark after the character string '2020-09-15 18:'.
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near '2020-09-15 18:'
There must be something wrong with the datetime variable.
Can anybody suggest how this should be done properly ?
declare #paramDailyOutput nvarchar(100), #retrieveDailyVal real
declare #paramDaily float
declare #retrieveDailyID varchar(100) = 'table_53'
declare #startTime datetime, #currTime datetime = GETDATE()
set #startTime = DATEADD(hour, -1, #currTime)
set #paramDailyOutput = 'SELECT #paramDaily = max(value) - min(value) FROM ' + #retrieveDailyID + ' where read_date between ''' + convert(nvarchar(200), #startTime, 120) + ''' and ''' + convert(nvarchar(200), #currTime, 120) + ''''
exec sp_executesql #paramDailyOutput, N' #paramDaily float OUTPUT', #paramDaily = #paramDaily output
select #paramDaily
You strings are too short, you're going way over 100 characters.
Try changing everything to 250 or even 300 characters. Or better yet, NVARCHAR(1000).

Function to get Lat Long points for geography polygon SQL

I've created a function to return a string of the points within a multi-point geography field in MS-SQL. I was wondering if there is a better way of doing this? What I want to is supply a list of points as a Lat/Long co-ordinates to an external client who does not use SQL geography data types (they are using SQL Lite).
Create FUNCTION [dbo].GetLatLongForPolygon
(
#Perimeter GEOGRAPHY
)
RETURNS Varchar(max)
AS
BEGIN
declare #NumPoints as Int
declare #OutputString as varchar(max)
declare #latpoint as varchar(max)
declare #longpoint as varchar(max)
set #NumPoints = #Perimeter.STNumPoints()
while #NumPoints >0
begin
set #LatPoint = #Perimeter.STPointN(#NumPoints).Lat
set #longpoint = #Perimeter.STPointN(#NumPoints).Long
set #OutputString = concat (#OutputString, '(' , #latpoint, ',', #longpoint , '), ')
set #NumPoints = #NumPoints -1
End
RETURN left (#OutputString, len(#outputstring)-1)
GO
Yes. Yes there is. I'm using a tally table to eliminate the cursor and a standard idiom to emulate the missing string concatenation aggregate in T-SQL.
declare #g geography = geography::STLineFromText('LINESTRING(20 20, 21 21, 22 22)', 4236);
with cte as (
select #g.STPointN(n.Number) as [Point]
from dbadmin.dbo.Numbers as n
where n.Number <= #g.STNumPoints()
)
select stuff((
select ', ' + concat('(', Point.Lat, ', ', Point.Long, ')')
from cte
for xml path('')
), 1, 2, '')

SQL pivot need fill 0

Hi i have big problem with pivot ISNULL i try convert many topics to my code but i failed with this. Its my code with error:
DECLARE #PivotColumnHeaders VARCHAR(MAX);
SET #PivotColumnHeaders='';
SELECT #PivotColumnHeaders =#PivotColumnHeaders + '[' + CONVERT(VARCHAR,Magazyn1) + '],'
FROM
(
Select DISTINCT Pro.SC03002 as Magazyn1
From SC030700 as Pro
) as Topa
SET #PivotColumnHeaders = LEFT(ISNULL(#PivotColumnHeaders,0),LEN(#PivotColumnHeaders)-1)
DECLARE #Column VARCHAR(MAX);
set #Column =SUBSTRING(( select distinct ',IsNull(['+SC03003+'],0) as ['+SC03003+']' from SC030700 for xml path('')),2,8000)
DECLARE #cmd VARCHAR(MAX);
-Msg 8114, Level 16, State 5, Line 284(set #column)
Error converting data type varchar to numeric.
SET #cmd='
SELECT Pro.SC03001 , '+#Column+'
FROM
(
Select Pro.SC03001 , Pro.SC03002, Pro.SC03003
From SC030700 as Pro
) AS myProducts
PIVOT (SUM(SC03003) FOR SC03002 IN ('+#PivotColumnHeaders+')) dynamicpivot '
EXECUTE (#cmd)
try casting column SC03003 to a varchar since you're adding it to a string value.
set #Column =SUBSTRING(( select distinct ',IsNull(['+ CONVERT(VARCHAR, SC03003)+'],0) as [' + CONVERT(VARCHAR, SC03003) +']' from SC030700 for xml path('')),2,8000)
You need to cast those numeric columns to varchar explicitly so you can concatenate them to your string:
set #Column =SUBSTRING(( select distinct ',IsNull(['+CAST(SC03003 AS varchar(31))+'],0) as [SC03003]' from SC030700 for xml path('')),2,8000)

Convert table to text in result of a query

Result of a query is table,is it possible to write a query that convert this result to a text (for example imagine that result is a table with 4 rows with value 1 to 4 and convert it to 1,2,3,4)
Yes, you can do that using FOR XML PATH(''). For example:
create table test(col varchar(10))
insert into test values ('1'),('2'),('3'),('4')
select STUFF( (select ',' + col
from test
FOR XML PATH('')), 1, 1, '')
Try the below query
declare #Var varchar(1000);
set #var = ''
select #Var = #var + CONVERT(varchar, Column1) + ','
from Table1
select #var
Try this
DECLARE #result varchar(1000)
SET #result = ''
SELECT #result = #result + StudentId + ',' FROM Student WHERE condition = xyz
select substring(#result, 1, len(#result) -1 --trim extra "," at end
Op like
1,2,3,4,..........
Happy Coding

How to return a string in reverse separated by a special character in SQL?

I have a string like this "Planck, Albert, Bohr"
I want the output as "Bohr Albert Planck"
I want this done using SQL server. I saw many string split functions all return the data as a table and in the forward order. These don't server my purpose.
Any pointers will be helpful.
This what you want:
DECLARE #source VARCHAR(MAX)
DECLARE #dest VARCHAR(MAX)
DECLARE #lenght INT
SET #source = 'Planck, Albert, Bohr'
SET #dest = ''
WHILE LEN(#source) > 0
BEGIN
IF CHARINDEX(' ', #source) > 0
BEGIN
SET #dest = SUBSTRING(#source,0,CHARINDEX(' ', #source)) + ' ' + #dest
SET #source = LTRIM(RTRIM(SUBSTRING(#source,CHARINDEX(' ',
#source)+1,LEN(#source))))
END
ELSE
BEGIN
SET #dest = #source + ' ' + #dest
SET #source = ''
END
END
SELECT REPLACE(REPLACE(#dest,Char(44),''),Char(13), '')
Char(44) is the ASCII value for , so at last I am just replacing that character.
This will print Bohr Albert Planck.
If you use a split string function like this you can do something like this.
declare #S varchar(20) = 'Planck, Albert, Bohr'
select
(
select ltrim(s)+' '
from dbo.Split(',', #S)
order by pn desc
for xml path(''), type
).value('.', 'varchar(max)')
SQL Fiddle
Declare #inStr varchar(1000)='Planck, Albert, Bohr'
;WITH CTE AS(
select ltrim(rtrim(reverse(left(reverse(#instr),CHARINDEX(',',reverse(#instr),1)-1)))) as strg,RIGHT(reverse(#instr),LEN(reverse(#instr))-CHARINDEX(',',reverse(#instr),1)) as rem
union all
select CASE WHEN CHARINDEX(',',c.rem,1)>0 then ltrim(rtrim(reverse(left(rem,CHARINDEX(',',rem,1)-1)))) else reverse(rem) end,
CASE WHEN CHARINDEX(',',c.rem,1)>0 then RIGHT(c.rem,LEN(rem)-CHARINDEX(',',rem,1)) else '' end
from CTE c
where len(rem) > 0 --CHARINDEX(',',c.rem,1)>0
)
select stuff((select ' '+strg from CTE for xml path('')),1,1,'')

Resources