SQL Server 2008 OPENQUERY inside sp_executesql. Getting error incorrect syntax? - sql-server-2008

Code:
DECLARE #resultLast int, #siparisID nvarchar(21)
SET #siparisID = 2487
EXEC sp_executesql N'select * from OPENQUERY([MYSERVER],''Select ( [MYDB].[dbo].[FN_SIPARIS_YUKLEME_TUTARI](#siparisID , 20 ,
[MYDB].[dbo].[FN_DATE_CONVERT_TO_DATE]( GETDATE()) , ''''BUY''''))'' )', #siparisID,
N'#resultLast int output', #resultLast output;
I am trying to fetch data from linked server function. Also i need to send #siparisID parameter. I am getting incorrect syntax error. Help please...
Error:
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near '2487'.

You've defined #siparisID nvarchar(21) - but you're setting it to a numerical datatype.
So either define it as a numeric datatype like int or decimal(p,s):
DECLARE #siparisID INT
DECLARE #siparisID BIGINT
DECLARE #siparisID DECIMAL(16,2)
or else change the initialisation to
SET #siparisID = N'2487';

Related

Conversion failed when converting the nvarchar value '2151','1886' to data type int

I have the below query
DEClare #Plan_ID nvarchar(100)
set #Plan_ID=REPLACE('2151,1886',',',''',''')
and
SELECT distinct Plan_Dict_Id from REF_Plan_Dictionary WHERE
CAST(Plan_Dict_Id as int) in (#Plan_ID),
Pls help , Plan_Dict_Id datatype is INT, I want to pass the values to where , but getting error "Conversion failed when converting the varchar value '2151','1886' to data type int."
If this is one of the later versions of SQL Server then you could do something like this...
DECLARE #Plan_ID nvarchar(100)
SET #Plan_ID= '2151,1886'
SELECT DISTINCT Plan_Dict_Id
FROM REF_Plan_Dictionary d
JOIN string_split(#Plan_ID, ',') s ON d.Plan_Dict_Id = s.[value]
If you are using an older version you could put the whole statement in a string and then execute it, however you have a problem in your first line as you are not adding quotes around the string... I've accounted for that below.
DEClare #Plan_ID nvarchar(100) set #Plan_ID=REPLACE('2151,1886',',',''',''')
DECLARE #sql nvarchar(max)
SET #SQL = 'select distinct Plan_Dict_Id from REF_Plan_Dictionary where CAST(Plan_Dict_Id as int) in (''' + #Plan_ID + ''')'
EXEC (#sql)

Incorrect syntax while parsing JSON with OPENJSON

This is my SP, I am trying to parse this and the error
Incorrect syntax near '$.Role'
was shown.
The JSON is stored in a tables's column. What am I doing wrong?
CREATE PROCEDURE [dbo].[sp_GetKeyPersonRoleMinMax]
#SectionID INT,
#ProposalID INT
AS
SET NOCOUNT ON
Declare #FldKPRoleRequirementsList NVARCHAR(MAX)
Declare #FldName varchar(50)
DEclare #FldIncl varchar(50)
Declare #FldRequired varchar(50)
Declare #FldLabel varchar(max)
Declare #FldList varchar(max)
CREATE Table #RoleMinMaxTemp
(
ID INT IDENTITY(1, 1) ,
Role nvarchar(1000),
MinRoleCount INT,
MaxRoleCount INT
)
Declare Fld_Cursor Cursor For
SELECT FldName, FldIncl, FldRequired, FldLabel,FldList from tblFld where FldParent = 1367 AND FldName like 'FldKPRoleRequirementsList%'
SET NOCOUNT ON
Open Fld_Cursor
WHILE (##Fetch_Status = 0)
BEGIN
if (#FldName = 'FldKPRoleRequirementsList')
BEGIN
SET #FldKPRoleRequirementsList = #FldList
END
FETCH next from Fld_Cursor into #FldName, #FldIncl, #FldRequired, #FldLabel,#FldList
END
Close Fld_Cursor
Deallocate Fld_Cursor
IF(#FldKPRoleRequirementsList IS NOT NULL and Len(#FldKPRoleRequirementsList) >0)
BEGIN
INSERT INTO #RoleMinMaxTemp
SELECT *
FROM OPENJSON(#FldKPRoleRequirementsList,'$.FldRole')
WITH (
Role nvarchar(1000) '$.Role',
MinRoleCount INT '$.MinRoleCount',
MaxRoleCount INT '$.MaxRoleCount'
);
END;
What is the reason for this error? I am using SQL Server 2016.
Try changing you compactibility of SQL SERVER to 130. Your must be below that.
ALTER DATABASE <DatabaseName> SET COMPATIBILITY_LEVEL = 130
Use this script to change it.

Getting an error creating SQL Function (cannot convert to int) when no ints are expected

I am needing to grab data from one table and use a relationship to place it into another table. Long story short, I need to get back an array of IDs so I created a function to return them. I am only retrieving data which is IDs so all int values. The problem is when I invoke my function I get the error:
Conversion failed when converting the varchar value '/' to data type int.
But everything is cast as varchar so I have NO idea why this is happening. I know its dirty code but it is a high priority project with a tight deadline so I just need it to work. I am using SQL Server 2012. Any thoughts?
Function:
CREATE FUNCTION FactPersonList (#FactID varchar(100),
#delimiter char(1))
RETURNS varchar(8000)
AS
BEGIN
DECLARE #CharIDList varchar(8000)
DECLARE #id int
DECLARE #FinalTable TABLE (
factid int,
charid int
)
SET #CharIDList = CHAR(08) + #delimiter
INSERT INTO #FinalTable
SELECT DISTINCT
#FactID,
CharacterId
FROM KeyFactsCharacters
WHERE KeyFactID = #FactID
WHILE ((SELECT
COUNT(*)
FROM #FinalTable)
> 0)
BEGIN
SET #Id = (SELECT TOP 1
charid
FROM #FinalTable)
SET #CharIDList = CAST(#CharIDList + #Id + #delimiter AS varchar(8000))
END
SET #CharIDList = CAST(#CharIDList + CHAR(08) + '~' AS varchar(8000))
RETURN CAST(#CharIDList AS varchar(8000))
END
I invoke it using this:
SELECT dbo.FactPersonList(KeyFact.KeyFactId, '/') FROM KeyFactsCharacters, KeyFact
I'm not familiar with MS SQL (experience almost exclusively in MySQL), but I would guess that #CharIDList + #Id + #delimiter is causing the error; since #Id is defined as an int, MS SQL may be trying to coerce the other operands to int values as well (for addition rather than concatenation).

Table type parameter in a stored procedure cause operand type clash error

I want to give an array of identifiers as argument to a stored procedure.
The stored procedure looks like :
ALTER PROCEDURE [dbo].[SearchPerson]
#personType INT = NULL,
#city NVARCHAR(64) = NULL,
#siteIds IntegerList READONLY,
-- some other params...
AS
SELECT
-- some fields...
FROM dbo.PersonView AS pv
WHERE
(
(#personType IS NULL OR pv.PersonType = #personType) AND
(#city IS NULL OR pv.City LIKE '%' + #city + '%') AND
(pv.SiteId in (SELECT si.Value FROM #siteIds AS si)) AND
-- some other params filter...
)
The user table type looks like :
CREATE TYPE [dbo].[IntegerList] AS TABLE(
[Value] [int] NULL
)
When I call the stored procedure from a script in SSMS (I originally have the same problem calling it from .NET code) :
DECLARE #siteIds AS IntegerList,
#personType AS INT = 1
INSERT INTO #siteIds VALUES (1)
EXEC [dbo].[SearchPerson] #personType, #siteIds
I got the error :
Operand type clash: int is incompatible with IntegerList
I found the answer : it was the order of the table type parameter that caused the error !
The table type parameter must be the first in the stored procedure parameters AND ALSO in the arguments passed to the stored procedure call !
The stored procedure :
ALTER PROCEDURE [dbo].[SearchPerson]
#siteIds IntegerList READONLY, -- THIS PARAMETER HAS TO BE THE FIRST !
#personType INT = NULL,
#city NVARCHAR(64) = NULL,
-- some other params...
AS
SELECT
-- some fields...
FROM dbo.PersonView AS pv
WHERE
(
(#personType IS NULL OR pv.PersonType = #personType) AND
(#city IS NULL OR pv.City LIKE '%' + #city + '%') AND
(pv.SiteId in (SELECT si.Value FROM #siteIds AS si)) AND
-- some other params filter...
)
And the call :
DECLARE #siteIds AS IntegerList,
#personType AS INT = 1
INSERT INTO #siteIds VALUES (1)
EXEC [dbo].[SearchPerson] #siteIds, #personType -- PUT #siteIds FIRST !
A sql server bug or am I missing something ?
DECLARE #ErrMsg varchar(1000)
DECLARE #ServiceDates ServiceDatesType
INSERT #ServiceDates (indexId,unitOfDay,dayOfMonth,dateOfMonth)
VALUES
(0,1,11,'9/11/2016 12:00:00 AM'),
(1,1,12,'9/12/2016 12:00:00 AM'),
(2,1,13,'9/13/2016 12:00:00 AM')
EXEC [usp_SaveValidate] 427,4,12,9,2016,#ErrMsg output,#ServiceDates
PRINT #ErrMsg
*/
ALTER PROCEDURE [dbo].[usp_SaveValidate] (
#EpisodeNo INT
,#ProviderId INT
,#ServiceId INT
,#Month INT
,#Year INT
,#ErrorMessage VARCHAR(1000) OUTPUT
,#ServiceDates ServiceDatesType ReadOnly
)
AS
BEGIN
-- Code Here
END
SQL SERVER 2012 - location of table type parameter does not matter, you have to make sure sequence while passing data, you can check above code which is working fine where table type parameter is at the last.

Function SQL Server 2008

I created the following function yesterday, and now I am facing an error:
Invalid length parameter passed to the left or substring function
Could you guys have a look at my function?I really appreciate it.
Create function nowFunctionNewadd
(#fladd varchar(255))
returns #tbl table(addr varchar(100), city varchar(100),
state varchar(100), Zip varchar(5))
as
begin
declare #str varchar(100)
,#i int
,#j int
,#str2 varchar(100)
,#address varchar(100)
,#city varchar(100)
,#lastcomma int
,#lastPart varchar(100)
,#zipstart int
,#zip varchar(5) = ''
select #str=rtrim(ltrim(#fladd))
set #i = charindex(',', #str)
set #str2=rtrim(ltrim(substring(#str, #i+1, 999)))
set #j=CHARINDEX(',',#str2)
set #lastcomma = len(#str) - charindex(',', reverse(#str)+',')
set #lastPart = substring(#str, #lastcomma+2, 100)
set #address = REPLACE(rtrim(ltrim(substring(#str,1,#i-1))),',','')
set #zipstart = patindex('%[0-9]%', #lastpart)
set #city=LTRIM(RTRIM(substring(#str, #i+1, #j-1)))
If #zipstart > 0
select #zip = substring(#lastpart, #zipstart, 5),
#lastPart = rtrim(substring(#lastpart, 1, #zipstart-1))
insert into #tbl(addr, city, state, Zip)
values(#address, #city, #lastpart, #zip)
return
end
The problem that I can see with your function starts with this line:
set #j=CHARINDEX(',',#str2)
And then I am guessing that the error is being thrown by this line:
set #city=LTRIM(RTRIM(substring(#str, #i+1, #j-1)))
Your function is working under the assumption that you will have more than one comma present in the string value that you are passing. But if you don't have more than one comma the value for #j will be zero and then you are trying to use a -1 as the length of the city and this will fail throwing the error you are getting.
I created a SQL Fiddle with a demo to work with. Using the address '1234 S.Alameda way,LA,CA12345' your function will work.
But if you change the value to '1234 S.Alameda way,LACA12345' it will fail
See SQL Fiddle Demo
Do you know what the format is going to be for all of the values that you need to pass into the function? If this format is going to change from 1 to 2 or even 3 commas I think you need to rethink how this function is written because it will not work as expected.