I created the following function in SQL 2008
CREATE FUNCTION dbo.udfSetSupplyStatus(#strOrderID nvarchar(16), #intLineNo int, #intOrderQty int, #strPartID nvarchar(16), #strWarehouseID nvarchar(16), #dtAsOfDate datetime, #strCalcMode nvarchar(16))
RETURNS nvarchar(32)
AS
BEGIN
DECLARE #strReturnValue nvarchar(32), #intQtyOnHand int, #intQtyOnOrder int, #intQtyPlanned int, #dtWantDate datetime
IF (#strCalcMode = 'S')
BEGIN
SELECT
#intQtyOnHand = (pw.available_qty + pw.committed_co + pw.committed_req + pw.committed_ibt + pw.locked_qty),
#intQtyOnOrder = (pw.expected_po + pw.expected_wo)
FROM VE_PART_WAREHOUSE as pw
INNER JOIN VE_PART as p on pw.part_id = p.id
WHERE pw.part_id = #strPartID
and pw.warehouse_id = #strWarehouseID
END
BEGIN
select
#dtWantDate = WANT_DATE,
#intQtyPlanned = ORDER_QTY
from VE_PLANNED_ORDER
where PART_ID = #strPartID
AND WAREHOUSE_ID = #strWarehouseID
END
IF(#intQtyOnHand >= #intOrderQty)
SET #strReturnValue = 'InStock'
ELSE IF(#intQtyOnHand + #intQtyPlanned) >= #intOrderQty
SET #strReturnValue = 'Expected'
ELSE
SET #strReturnValue = 'NoSupply'
RETURN #strReturnValue
END
I can see the function in the Scalar-valued Functions under Programmability in the Database I'm using but when I try to call the function Intellisense doesn't detect my function.
Related
This trigger was not written by me or used with a stored proc original I modified it for my use. The problem to me appears to be one of permissions when the table is manually updated or inserted inSQL Server Management Studio the trigger works perfectly. When the Trigger is updated or inserted by a Stored Proc ran via an ODBC connection it does not modify the table and the Trigger does not work. If the trigger is disabled the stored Proc works as expected. So the error appers to be some form of permission error. Here is the trigger. (Using 2012)
Thanks In Advance
Donald S. Bossen
USE [JBI]
GO
/****** Object: Trigger [dbo].[send_ship_exec_info_to_p21] Script Date: 8/29/2018 3:22:26 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER TRIGGER [dbo].[send_ship_exec_info_to_p21] ON [dbo].[ship_exec]
FOR INSERT, UPDATE
AS
declare #pick_ticket_no varchar(50)
declare #tracking_no varchar(50)
declare #pickup_date varchar(50)
declare #carrier_id varchar(50)
declare #package_count varchar(50)
declare #delete_flag varchar(50)
declare #package_weight varchar(50)
declare #package_charge decimal(9,4)
declare #total_shipment_charge decimal(19,4)
declare #carrier_name varchar(50)
declare #customer_freight_charge decimal(9,4)
declare #saturday_delivery varchar(50)
declare #transaction_type varchar(50)
declare #billing_option varchar(3)
select
#pick_ticket_no = i.pick_ticket_no,
#tracking_no = i.tracking_no,
#pickup_date = i.pickup_date,--left(i.pickup_date,8),
#carrier_id = i.service_type,
#package_count = i.package_count,
#delete_flag = i.delete_flag,
#package_weight = i.package_weight,
#package_charge = i.package_charge,
#total_shipment_charge = i.total_shipping_and_handling_charge,
#saturday_delivery = i.saturday_delivery,
#transaction_type = i.transaction_type,
#billing_option = i.billing_option
from inserted i
if #transaction_type = 'Inv Return'
begin
declare #document_link_uid int
declare #document_link_area_uid int
declare #link_name varchar(255)
declare #link_path varchar(4099)
set #link_name = 'UPS shipment ' + cast(#pick_ticket_no as varchar(40)) + ': ' + #tracking_no
set #link_path = 'http://wwwapps.ups.com/WebTracking/processInputRequest?HTMLVersion=5.0&sort_by=status&term_warn=yes&tracknums_displayed=5&TypeOfInquiryNumber=T&loc=en_US&InquiryNumber1=' + #tracking_no + '&InquiryNumber2=&InquiryNumber3=&InquiryNumber4=&InquiryNumber5=&AgreeToTermsAndConditions=yes&track.x=28&track.y=2'
if #delete_flag = 'Y'
begin
update
PROPHET21.dbo.document_link
set
row_status_flag = '700'
,date_last_modified = getdate()
,last_maintained_by = 'Ship Exec Delete Flag'
where
key1_cd = 'return_number'
and key1_value = #pick_ticket_no
and link_path like '%' + #tracking_no + '%'
end
if #delete_flag = 'N'
begin
if not exists(select document_link_uid from PROPHET21.dbo.document_link where link_path like '%' + #tracking_no + '%')
begin
exec #document_link_uid = PROPHET21.dbo.p21_get_counter 'document_link', 1
INSERT INTO
PROPHET21.dbo.document_link
(
document_link_uid
,source_area_cd
,key1_cd
,key1_value
,link_name
,link_path
,row_status_flag
,date_created
,created_by
,date_last_modified
,last_maintained_by
,outside_use_flag
,mandatory_flag
)
VALUES
(
#document_link_uid
,1312
,'return_number'
,#pick_ticket_no
,#link_name
,#link_path
,704
,getdate()
,'SHIP EXEC'
,getdate()
,'SHIP EXEC'
,'N'
,'N'
)
exec #document_link_area_uid = PROPHET21.dbo.p21_get_counter 'document_link_area', 1
INSERT INTO
PROPHET21.dbo.document_link_area
(
document_link_area_uid
,document_link_uid
,display_area_cd
,row_status_flag
,date_created
,created_by
,date_last_modified
,last_maintained_by
)
VALUES
(
#document_link_area_uid
,#document_link_uid
,1312
,704
,getdate()
,'SHIP EXEC'
,getdate()
,'SHIP EXEC'
)
end
end
end
if #transaction_type <> 'SWS' or not exists(select oe_pick_ticket.pick_ticket_no from PROPHET21.dbo.oe_pick_ticket oe_pick_ticket where oe_pick_ticket.pick_ticket_no = #pick_ticket_no)
return
if #transaction_type = 'SWS' and exists(select oe_pick_ticket.pick_ticket_no from PROPHET21.dbo.oe_pick_ticket oe_pick_ticket where oe_pick_ticket.pick_ticket_no = #pick_ticket_no)
begin
if (#delete_flag = 'Y')
begin
declare #invoiced_already varchar (50)
select #invoiced_already = oe_pick_ticket.invoice_no
from PROPHET21.dbo.oe_pick_ticket oe_pick_ticket
where pick_ticket_no = #pick_ticket_no
if(#invoiced_already is null)
begin
update PROPHET21.dbo.clippership_return_10004
set delete_flag = 'Y'
where tracking_no = #tracking_no
update PROPHET21.dbo.oe_pick_ticket
set freight_out = 0, date_last_modified = getdate(), last_maintained_by = 'Ship Exec void package'
where pick_ticket_no = #pick_ticket_no
end
return
end
if (#delete_flag = 'N')--#tracking_no like '1z%' and
Begin
declare #customer_pays_outgoing_freight char(1)
select
#customer_pays_outgoing_freight = freight_code.outgoing_freight
from
PROPHET21.dbo.oe_pick_ticket oe_pick_ticket
inner join PROPHET21.dbo.freight_code freight_code on oe_pick_ticket.freight_code_uid = freight_code.freight_code_uid and oe_pick_ticket.company_id = freight_code.company_id
where
oe_pick_ticket.pick_ticket_no = #pick_ticket_no
select
#carrier_name = carrier.name
from
PROPHET21.dbo.address carrier
where
carrier.id = #carrier_id
select #customer_freight_charge =
cast(case
when #billing_option in ('REC', 'TP', 'CB') then 0
when coalesce(#customer_pays_outgoing_freight, 'Y') = 'N' then 0
else ((#total_shipment_charge) / #package_count)
end as decimal(19,2))
update PROPHET21.dbo.oe_pick_ticket
set freight_out = isnull(freight_out, 0) + isnull(#customer_freight_charge, 0),
carrier_id = #carrier_id,
tracking_no = #tracking_no
where pick_ticket_no = #pick_ticket_no
insert into PROPHET21.dbo.clippership_return_10004
(pick_ticket_no,
tracking_no,
package_weight,
order_count,
shipped_date,
carrier_name,
total_charge,
processed_flag,
delete_flag,
date_created,
date_last_modified,
last_maintained_by,
line_number)
values
(#pick_ticket_no,
#tracking_no,
#package_weight,
#package_count,
#pickup_date,
#carrier_name,
#customer_freight_charge,
'N',
'N',
getdate(),
getdate(),
'SHIP EXEC',
0)
end
return
End
UPDATE SampleTable
SET Schemaname = #SchemaName,
SchemaCode = #SchemaCode,
ForeignKeyColumn = #ForeignKeyColumn,
IsChildSchema = #IsChildSchema,
ModifiedBy = #ModifiedBy,
ModifiedDate = #ModifiedDate
WHERE
DataSchemaID = #DataSchemaId
My #ForeignKeyColumn parameter is
2233^SITE_CLM_NUMBER,2236^SITE_ID_N,
Can anyone help me in updating ForeignKeyColumn='SITE_CLM_NUMBER' where DataSchemaID=2233 and ForeignKeyColumn='SITE_ID_N' where DataSchemaID=2236
It's easy to pass multiple parameter values to a query, using a Table Valued Parameter. These are available in all versions of SQL Server since 2008.
First, you need to create a Table type with the fields you want:
CREATE TYPE dbo.KeyValueType AS TABLE
( Key int, Value nvarchar(50) )
This allows you to specify a parameter of type KeyValueType with the Key/Value combinations you want, eg #updatedColumns.
You can join the target table with the TVP to update rows with matching DataSchemaID values:
Create Procedure UpdateSchemas(...., #updatedColumns dbo.KeyValueType)
UPDATE SampleTable
SET
Schemaname=#SchemaName
,SchemaCode=#SchemaCode
,ForeignKeyColumn=t.Value
,IsChildSchema=#IsChildSchema
,ModifiedBy=#ModifiedBy
,ModifiedDate=#ModifiedDate
FROM SampleTable
INNER JOIN #updatedColumns t
ON t.ID=DataSchemaID
You can add an SplitString function, like this one :
How to Split String by Character into Separate Columns in SQL Server
CREATE FUNCTION [dbo].[Split]
(
#String varchar(max)
,#Delimiter char
)
RETURNS #Results table
(
Ordinal int
,StringValue varchar(max)
)
as
begin
set #String = isnull(#String,'')
set #Delimiter = isnull(#Delimiter,'')
declare
#TempString varchar(max) = #String
,#Ordinal int = 0
,#CharIndex int = 0
set #CharIndex = charindex(#Delimiter, #TempString)
while #CharIndex != 0 begin
set #Ordinal += 1
insert #Results values
(
#Ordinal
,substring(#TempString, 0, #CharIndex)
)
set #TempString = substring(#TempString, #CharIndex + 1, len(#TempString) - #CharIndex)
set #CharIndex = charindex(#Delimiter, #TempString)
end
if #TempString != '' begin
set #Ordinal += 1
insert #Results values
(
#Ordinal
,#TempString
)
end
return
end
Now you can easily extract each part of your input parameter.
declare #I int;
declare #TMP nvarchar(255);
set #I = 1;
set #TMP = null;
set #TMP = (select StringValue from Split(#ForeignKeyCoumn, ',') where Ordinal = 1);
while #TMP <> null
begin
set #ForeignKeyColumn = (select StringValue from Split(#TMP, '^') where Ordinal = 1);
set #DataSchemaID = (select StringValue from Split(#TMP, '^') where Ordinal = 2);
-- Update here your table with #ForeignKeyColumn and #DataSchemaID values
set #I = #I + 1;
set #TMP = null;
set #TMP = (select StringValue from Split(#ForeignKeyCoumn, ',') where Ordinal = #I);
end
PS: If your are using SQL Server 2016 it already includes an SplitString function, so you won't need to add your own. https://learn.microsoft.com/en-us/sql/t-sql/functions/string-split-transact-sql
I have a SQL based report that I am migrating from Crystal Reports to SSRS. The old method uses a stored procedure that calls a stored function. The intent in the new method is to embed all of the report logic in the SSRS report. The reason behind this is that the stored procedure and function are not part of the target database. We don't want to have an extra database that just holds a few stored functions and procedures.
The basic structure now is:
select (a bunch of fields)
from (a bunch of joins)
where (conditions)
and specific_value in (select value
from stored_function(inputs)
)
The stored function does some delimiter processing. I need to run this in SSRS only, without storing anything in the database. I can convert the stored procedure into a dataset in SSRS, but I can't figure out how to handle the stored_function.
-----edit ----- Here is the code in questions:
CREATE FUNCTION [dbo].[fn_split] (
#SourceString sql_variant,
#Delimiter nvarchar(10) = N',')
RETURNS #Values TABLE(Position smallint IDENTITY, cValue varchar(2000) , ncValue nvarchar(2000))
AS
BEGIN
DECLARE #NormalString varchar(2000), #NationalString nvarchar(2000),
#NormalDelimiter varchar(10), #NationalDelimiter nvarchar(10),
#IsNationalChar bit, #Position int,
#NormalValue varchar(2000), #NationalValue nvarchar(2000)
SET #Delimiter = COALESCE(#Delimiter, N',')
SET #IsNationalChar = CASE
WHEN SQL_VARIANT_PROPERTY(#SourceString,'BaseType') IN ('char','varchar')
THEN 0
WHEN SQL_VARIANT_PROPERTY(#SourceString,'BaseType') IN ('nchar','nvarchar')
THEN 1
END
IF #IsNationalChar IS NULL RETURN
IF #IsNationalChar = 0
BEGIN
SET #NormalDelimiter = #Delimiter
SET #NormalString = CAST(#SourceString AS varchar(2000))
IF LEFT(#NormalString,LEN(#NormalDelimiter)) = #NormalDelimiter
SET #NormalString = SUBSTRING(#NormalString,LEN(#NormalDelimiter) + 1, 2000)
IF RIGHT(#NormalString,LEN(#NormalDelimiter)) <> #NormalDelimiter
SET #NormalString = #NormalString + #NormalDelimiter
WHILE(1 = 1)
BEGIN
SET #Position = CHARINDEX(#NormalDelimiter,#NormalString) - 1
IF #Position <= 0 BREAK
SET #NormalValue = LEFT(#NormalString,#Position)
SET #NormalString = STUFF(#NormalString,1,#Position + LEN(#NormalDelimiter),'')
INSERT INTO #Values(cValue) VALUES(#NormalValue)
END
END
ELSE IF #IsNationalChar = 1
BEGIN
SET #NationalDelimiter = #Delimiter
SET #NationalString = CAST(#SourceString AS varchar(2000))
IF LEFT(#NationalString,LEN(#NationalDelimiter)) = #NationalDelimiter
SET #NationalString = SUBSTRING(#NationalString,LEN(#NationalDelimiter) + 1,2000)
IF RIGHT(#NationalString,LEN(#NationalDelimiter)) <> #NationalDelimiter
SET #NationalString = #NationalString + #NationalDelimiter
WHILE(1 = 1)
BEGIN
SET #Position = CHARINDEX(#NationalDelimiter,#NationalString) - 1
IF #Position <= 0 BREAK
SET #NationalValue = LEFT(#NationalString,#Position)
SET #NationalString = STUFF(#NationalString,1,#Position + LEN(#NationalDelimiter),'')
INSERT INTO #Values (ncValue) VALUES(#NationalValue)
END
END
RETURN
END
That function gets called at the end of the query (fn_split).
select (a bunch of fields)
from (a bunch of joins)
where (conditions)
and specific_value in (select value
from stored_function(input_value)
)
I'm trying to recreate this without using a Database Object (function or procedure). I'm okay with code in the SSRS report.
Just an idea. You could use 2 datasets :
select (a bunch of fields)
from (a bunch of joins)
where (conditions)
and specific_value in #Algo
and
select value
from stored_function(inputs)
I have the following spr, and when trying to create i get an error about declaring the scalar variable insertvalues. I have created a type, redirect.
CREATE TYPE Redirect AS TABLE(
RED_ID INT,
RED_Type int,
RED_FromURL varchar(max),
RED_ToURL varchar(max),
RED_StartDate datetime,
RED_EndDate datetime
);
Below is the stored procedure, which is facing the problems. (With the update where it uses #insertValues.RED_Type
CREATE PROCEDURE [dbo].[AddUpdateRedirects]
#insertValues Redirect READONLY
AS
BEGIN
DECLARE #updateRowsAffected AS INT
DECLARE #insertRowsAffected AS INT
--Update
UPDATE
tbl_Redirects
SET
RED_Type = #insertValues.RED_Type,
RED_FromURL = #insertValues.RED_FromURL,
RED_ToURL = #insertValues.RED_ToUrl,
RED_StartDate = #insertValues.RED_StartDate,
RED_EndDate = #insertValues.RED_EndDate,
RED_DateUpdated = GETDATE()
FROM #insertValues
WHERE tbl_Redirects.RED_ID = #insertValues.RED_ID
AND #insertValues.RED_ID <> 0
SET #updateRowsAffected = ##ROWCOUNT
INSERT INTO
tbl_Redirects
(
RED_Type,
RED_DateCreated,
RED_FromURL,
RED_ToURL,
RED_StartDate,
RED_EndDate
)
SELECT iv.RED_Type,
GETDATE(),
iv.RED_FromURL,
iv.RED_ToUrl,
iv.RED_StartDate,
iv.RED_EndDate
FROM #insertValues iv
LEFT JOIN tbl_Redirects rd ON rd.RED_FromURL = iv.RED_FromURL
WHERE iv.RED_ID = 0 -- Where it's a new record
AND rd.RED_ID IS NULL -- and where the FromURL doesn't currently exist
SET #insertRowsAffected = ##ROWCOUNT
SELECT #updateRowsAffected + #insertRowsAffected as TotalRowsAffected
END
You just need to wrap the table name in square brackets:
UPDATE tbl_Redirects
SET RED_Type = [#insertValues].RED_Type ,
RED_FromURL = [#insertValues].RED_FromURL ,
RED_ToURL = [#insertValues].RED_ToUrl ,
RED_StartDate = [#insertValues].RED_StartDate ,
RED_EndDate = [#insertValues].RED_EndDate ,
RED_DateUpdated = GETDATE()
FROM #insertValues
WHERE tbl_Redirects.RED_ID = [#insertValues].RED_ID
AND [#insertValues].RED_ID <> 0
Or as Zohar Peled states give it an alias:
UPDATE tbl_Redirects
SET RED_Type = t.RED_Type ,
RED_FromURL = t.RED_FromURL ,
RED_ToURL = t.RED_ToUrl ,
RED_StartDate = t.RED_StartDate ,
RED_EndDate = t.RED_EndDate ,
RED_DateUpdated = GETDATE()
FROM #insertValues t
WHERE tbl_Redirects.RED_ID = t.RED_ID
AND t.RED_ID <> 0
is it possible in T SQL to use a function as a while parameter? I have the following code:
create function LoginExists (#p_login char(6))
returns varchar(5)
begin
if exists(select * from Student where student.slogin = #p_login)
return 'true'
return 'false'
end;
and
create procedure AddStudent2
(#p_fname varchar(30), #p_lname varchar(50), #p_tallness int)
as
declare #p_login char(6), #p_email varchar(50), #suffix char(3);
set #p_lname = LOWER(#p_lname);
set #suffix = '000';
begin
set #p_login = substring(#p_lname,1, 3) + #suffix;
while (LoginExists #p_login = 'true')
set #suffix = cast((CAST(#suffix as int) + 1) as char(3));
set #p_login = substring(#p_lname,1, 3) + #suffix;
set #p_email = #p_login + '#vsb.cz';
insert into Student values (#p_login, #p_fname, #p_lname, #p_email, #p_tallness);
end;
and when trying to compile it, an error occurs, saying: "Incorrect syntax near '#p_login'."
Your syntax for calling a function is in fact incorrect:
Replace:
while (LoginExists #p_login = 'true')
with:
while (dbo.LoginExists (#p_login)= 'true')
Replace
if exists(select * from Student where student.slogin = #p_login)
by
if exists(select * from Student where Student.slogin = #p_login)
Upper 'S' in student.slogin and i hope it work