Casting in crystal (ntext to varchar)
Hi,
There is a field in my database that is of type ntext. I want to change this to varchar. What would i write in a formula to do this?
Note: I cannot change the column type in the database itself.
Thanks
J.
totext(Database_Field)
Thanks
-Azhar
Similar Messages
-
Casting of crystal report viewer
I want to load crystal report in SAP B One.For this I have created a form through screen painter.I am trying to load crystal report on this form.I am using following code-
Dim objCRViewer As New CrystalActiveXReportViewerLib10.CrystalActiveXReportViewer
Dim objReport As CRAXDDRT20.Report
objDT = GetData("Select * from OUSR")
'Datable objDT created as per requirement
objReport = objAppl.OpenReport("F:\Final\sdk\Crystal Report\CrystalReport\rptUsers.rpt")
objReport.Database.SetDataSource(objDT)
objCRViewer.DisplayToolbar = True
objCRViewer.DisplayGroupTree = True
objCRViewer.EnableExportButton = True
objCRViewer.ReportSource = objReport
objCRViewer.RefreshEx(True)
objCRViewer.ViewReport()
The above code does not create any problem.I want to add objCRViewer in the form.The method of adding a control is,
oForm = SBO_Application.Forms.ActiveForm
oForm.Items.Add("objCRViewer", SAPbouiCOM.BoFormItemTypes.it_ACTIVE_X)
In BoFormItemTypes crystal report viewer is not present.How do I cast the crystal report viewer to activex control ?Hi Dilip,
I guess its not possible to load a Crystal viewer in SBO form. Generally i use a windows form to show my crystal reports.
If its possible to use Crystal viewer in SBO form, it will be great. Hope u'll be able to solve this problem so that i can use ur approach.
Regards,
Vasu Natari. -
Crystal reports converting varchar 254 to memo data type
Hi All,
We are still using Seagate Crystal Reports 7.5 for some of our reporting. I have a problem that hopefully someone can help with. One of our connections is to ODBC- AR System ODBC Data Source.
In that data source there are fields defined as varchar 254 (confirmed by DBA),
But Seagate is calling them memo fields- which is causing problems since you canu2019t use memos in selection criteria or formulas.
This happened after the field names were renamed. I noticed when the newly named fields were not showing as an option to map the old name fields to- because by default it looks for same data type, after unchecking same data type option the fields showed for mapping but wrong data type makes them useless. I canu2019t even convert them to string with formula field.
Any input would be greatly appreciated.
Thanks-Hi,
Yup, this was a problem with versions prior to 10. If a field was longer than 254 characters, Crystal handled them like Memos and you cannot use them in formulas.
The only suggestion I can offer would be to upgrade. Crystal can now use memos in formulas and no longer has a 254 character limit on strings. So your charcter fields will remain as charater and not changed to Memos.
Good luck,
Brian -
Hi all,
Any idea why the timestamp is lost after casting a date into a varchar (FYI : datatype is datetime in the rpd)
if I have a date like ;
date = 5/2/2011 9:18:26 AM
CAST (date as varcchar(100)) gives 5-2-2011
Is there anyway to avoid this lost of precision
Best regards
AdilHi adil,
To eliminate timestamp,which i faced long back was a horrifying task.So i used trunc function this way
You can do this way by going to physcial layer of RPD and go to the table the date column is coming from
1) go to properties of the table
2) go to general tab and change the table type to SQL
3) Write the SQL by selecting required columns from that table including this date column i.e.
select x,y,trunc(date_column) from table_name
This way the timestamp will be gone.
CAST (date as varcchar(100)) gives 5-2-2011 I suppose as your converting it to varchar,it is assuming it as a string and omitting precision but changing to default date format(dd-mon-yy).
UPDATED POST
Ok got you wrong,so you want the he precision while converting it to char so you need to use evaluate with char and give the format and precision the way you require.
hope helps you.
Cheers,
KK
Edited by: Kranthi.K on Jun 1, 2011 10:16 PM -
Hi expert,
regarding crystal report query,im still new in crystal report,actually i want to make report join with table opor,por1,opor,oitm,oshp,nnm1,ocrn,por10 and octg.im face difficulty when want to join por10.then i join with por10.docentry = por1.docentry with table por1 and por1.visorder = por10.aftlinenum and im not sure it correct or not.im just want to make condition like this
if (T1.U_CSUS_Size = '') and (t2.LineType = 'T') then it will show (t0.U_CSUS_ItmCode + ' ' + t0.U_CSUS_ItmDescp + ' ' + t1.U_CSUS_Size) else (t0.U_CSUS_ItmCode + ' ' + t0.U_CSUS_ItmDescp) and joining (from POR1 T0
INNER JOIN OITM T1 ON T0.ItemCode = T1.ItemCode
inner join por10 T2 on T0.docentry = T2.docentry and T0.visorder = T2.aftlinenum)
for 'u_csus_.....' is for udf i created.can i know how easier step for this condition.i also already try alot of query.sometime can make duplicate column.
regards,
Arif
Edited by: Ahmad Arif on Jan 10, 2012 4:03 AMDear Anmad Arif
Try the below query
SELECT
(CASE WHEN (T1.U_CSUS_Size = '') and (t2.LineType = 'T') THEN
(t0.U_CSUS_ItmCode + ' ' + t0.U_CSUS_ItmDescp + ' ' + t1.U_CSUS_Size)AS NVARCHAR(1000))
else T1.[Dscription] End) AS [Description],
T1.VisOrder,
(CASE WHEN T1.[Quantity]<=0 THEN NULL ELSE T1.[Quantity] END) AS Qty,
CAST(ISNULL(T3.UserText, '''') AS VARCHAR(MAX)) As ItemDesc,
T1.Currency, T3.SuppCatNum,
(CASE WHEN T1.linetotal<=0 THEN NULL ELSE T1.linetotal END) as amount,
(CASE WHEN T1.[price]<=0 THEN NULL ELSE T1.[price] END) AS Rate,
T3.UserText,
T0.DocEntry,
ISNULL(T1.U_Unit, T3.SalUnitMsr) AS SaleUnit,
ISNULL(T3.BuyUnitMsr, '''') AS PurchaseUnit,T1.VisOrder,'' LineSeq,'' aftLineNum,
ISNULL(T0.U_QText,'') AS QText,T1.U_QRR as QRR
FROM OPOR T0
RIGHT OUTER JOIN POR1 T1 ON T0.DocEntry = T1.DocEntry
RIGHT OUTER JOIN OITM T3 ON T1.ItemCode = T3.ItemCode
LEFT OUTER JOIN dbo.OSCN AS T4 ON (T0.CardCode=T4.CardCode AND T1.ItemCode=T4.ItemCode)
WHERE T0.Docnum = '4063'
UNION ALL
SELECT CAST(ISNULL(T1.LineText, '') AS VARCHAR(MAX)) AS [Description],
T1.AftLineNum,
NULL Qty,
null,
null ,NULl ,NULL,
null Rate,
NULL,
T0.DocEntry,
null,
null,T1.OrderNum,T1.LineSeq,AftLineNum,'' AS BPCatlog,
null
FROM OPOR T0
RIGHT OUTER JOIN POR10 T1 ON T0.DocEntry = T1.DocEntry
WHERE T0.Docnum = '4063'
And T1.LineText IS NOT NULL
Note : Change the DocNum= DocKey When you use Crystal report As per your requied
Regards
Kamlesh -
CAST,CONVERT and SUBSTRING
Hi,
I have a coumn called Date
DAte: 2014-05-12 00:00:00.000 (yyyy-mm-dd time)
Now i need to change this to two Column called Season and DateMM
where
DateMM: 201405 (yyyymm) and
season : FA14 ( since its a fifth month I want to call it as FA and the 14 is from 2014).
Anyone who can help?
SPPandeyAre the seasons defined
considering northern or southern hemisphere?
The
beginning and
end of each season
varies
according to the hemisphere
and even
country.Vide
equinox and
solstice.
Try
-- code #1
;with
Frank as (
SELECT [Date], AAAAMM= Convert(char(6), [Date], 112),
MMDD= Right( Convert(char(8), [Date], 112), 4)
from ...
SELECT [Date],
DateYM= AAAAMM,
Season= case when MMDD >= '0320' and MMDD < '0620' then 'AU'
when MMDD >= '0621' and MMDD < '0922' then 'WI'
when MMDD >= '0923' and MMDD < '1221' then 'SP'
else 'SU' end +
Right('00' + Cast((Year([Date]) % 100) as varchar), 2)
from Frank;
or
-- code #2
CREATE FUNCTION SeasonYear (@Date date)
returns char(2) as
begin
declare @MMDD char(4), @S char(2);
set @MMDD= Right( Convert(char(8), @Date, 112), 4);
set @S= case when @MMDD >= '0320' and @MMDD < '0620' then 'AU'
when @MMDD >= '0621' and @MMDD < '0922' then 'WI'
when @MMDD >= '0923' and @MMDD < '1221' then 'SP'
else 'SU' end;
return @S;
end;
go
SELECT [Date],
DateYM= Convert(char(6), [Date], 112),
Season= dbo.SeasonYear([Date]) +
Right(Convert(char(4), [Date], 112), 2)
from ...;
José Diz Belo Horizonte, MG - Brasil -
I am getting a MSG 306 ERROR. I think it is because one field is 30 Characters and other field is TEXT. Just guessing. Here is the code, error message and DDL.
Select SD.Sales_Order As [SO #]
,SD.SO_Line As [Ln]
,Cast(Min(SD.Status) As Varchar(1)) As [SS] ---Ln Status
,MIN(SH.Sales_Rep) As [Rep]
,MIN(SH.Customer) As [Cust ID]
,Min(SD.Material) As [Material/Part Number]
,(Case when SD.Material like '%CUSTOM-SPECIAL%' then SD.Ext_Description
when SD.Material Not like '%CUSTOM-SPECIAL%' then SD.Description
else '' end) [Description]
,MIN(Case when PATINDEX('Ship complete', SH.Comment)>0 then 'SC'
when PATINDEX('In CustomerID', SH.Comment)>0 then 'ICSL'
when SH.Ship_Via = 'Cust Stock' then 'CSTK'
when SH.Ship_Via = 'Install' then 'INST'
when SD.Status = 'Hold' then 'HOLD'
else '' end) [Txt]
,MIN(Case when PATINDEX('SO Given to Ron F', SH.Note_Text)>0 then 'RON F'
when SD.Job IS null then ''
When SD.Job IS Not null then SD.Job
else '' end) [Linked]
,MIN(ISNULL(SD.PO,'')) As [PO] ---- Linked PO
,Cast(MIN(ISNULL(J.Status,''))As Varchar(1))As [St] ---- Job Status
,Cast(SUM((SD.Order_Qty - SD.Shipped_Qty) * (100 - SD.Discount_Pct) * SD.Unit_Price / 100) As Decimal(7,2)) As [Ext Amt]
,Min(SD.Order_Qty)As [Ord]
,Min(SD.Picked_Qty)As [Pick]
,MIN(SD.Backorder_Qty)As [BO]
,Cast(Min(SH.Order_Date) As Date) As [Ord Date]
,Min(M.Lead_Days)As [LD]
,Cast(Min(SD.Promised_Date) As Date) As [Promised]
from [PRODUCTION].dbo.SO_Detail As SD
INNER JOIN [PRODUCTION].dbo.SO_Header As SH
on SD.Sales_Order = SH.Sales_Order
and(SD.Status = 'Open'
or SD.Status = 'Backorder'
or SD.Status = 'Hold' )
INNER JOIN [PRODUCTION].dbo.Material As M
on SD.Material = M.Material
LEFT OUTER JOIN [PRODUCTION].dbo.Job As J
On SD.Job = J.Job
Group by SD.Promised_Date, SD.Sales_Order, SD.SO_Line, SD.Description, SD.Ext_Description
Order by SD.Promised_Date, SD.Sales_Order, SD.SO_Line
ERROR MESSAGE
Msg 306, Level 16, State 2, Line 39
The text, ntext, and image data types cannot be compared or sorted, except when using IS NULL or LIKE operator.
DDL
SO_DETAIL
USE [PRODUCTION]
GO
/****** Object: Table [dbo].[SO_Detail] Script Date: 05/06/2014 15:45:55 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[SO_Detail](
[SO_DetailKey] [dbo].[KeyNum] IDENTITY(1,1) NOT NULL,
[SO_Detail] [dbo].[KeyNum] NULL,
[Sales_Order] [dbo].[Key10] NOT NULL,
[SO_Line] [dbo].[T_6] NOT NULL,
[PO] [dbo].[Key8] NULL,
[Line] [dbo].[T_6] NULL,
[Material] [dbo].[T_30] NULL,
[Ship_To] [int] NULL,
[Drop_Ship] [bit] NOT NULL,
[Quote] [varchar](50) NULL,
[Job] [dbo].[Key10] NULL,
[Status] [dbo].[T_9] NOT NULL,
[Make_Buy] [dbo].[T_1] NOT NULL,
[Unit_Price] [float] NOT NULL,
[Discount_Pct] [float] NOT NULL,
[Price_UofM] [dbo].[UofM] NOT NULL,
[Total_Price] [money] NOT NULL,
[Deferred_Qty] [float] NOT NULL,
[Prepaid_Amt] [money] NOT NULL,
[Unit_Cost] [float] NOT NULL,
[Order_Qty] [float] NOT NULL,
[Stock_UofM] [dbo].[UofM] NOT NULL,
[Backorder_Qty] [float] NOT NULL,
[Picked_Qty] [float] NOT NULL,
[Shipped_Qty] [float] NOT NULL,
[Returned_Qty] [float] NOT NULL,
[Certs_Required] [bit] NOT NULL,
[Taxable] [bit] NOT NULL,
[Commissionable] [bit] NOT NULL,
[Commission_Pct] [float] NOT NULL,
[Sales_Code] [dbo].[T_UCode] NULL,
[Note_Text] [text] NULL,
[Promised_Date] [datetime] NULL,
[Last_Updated] [datetime] NOT NULL,
[Description] [dbo].[T_30] NULL,
[Price_Unit_Conv] [float] NULL,
[Rev] [dbo].[T_8] NULL,
[Tax_Code] [dbo].[T_15] NULL,
[Ext_Description] [text] NULL,
[Cost_UofM] [dbo].[T_4] NULL,
[Cost_Unit_Conv] [float] NULL,
[Res_Type] [smallint] NULL,
[Res_ID] [dbo].[T_50] NULL,
[Res_Qty] [float] NULL,
[Partial_Res] [bit] NULL,
[Prepaid_Trade_Amt] [money] NULL,
[ObjectID] [uniqueidentifier] NOT NULL,
CONSTRAINT [PK_SO_Detail] PRIMARY KEY NONCLUSTERED
[SO_DetailKey] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
ALTER TABLE [dbo].[SO_Detail] WITH NOCHECK ADD CONSTRAINT [FK_SOH_on_SODetl] FOREIGN KEY([Sales_Order])
REFERENCES [dbo].[SO_Header] ([Sales_Order])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[SO_Detail] NOCHECK CONSTRAINT [FK_SOH_on_SODetl]
GO
ALTER TABLE [dbo].[SO_Detail] ADD CONSTRAINT [DF_SO_Detail_Drop_Ship] DEFAULT ((0)) FOR [Drop_Ship]
GO
ALTER TABLE [dbo].[SO_Detail] ADD CONSTRAINT [DF_SO_Detail_Status] DEFAULT ('Open') FOR [Status]
GO
ALTER TABLE [dbo].[SO_Detail] ADD CONSTRAINT [DF_SO_Detail_Make_Buy] DEFAULT ('M') FOR [Make_Buy]
GO
ALTER TABLE [dbo].[SO_Detail] ADD CONSTRAINT [DF_SO_Detail_Discount_Pct] DEFAULT ((0)) FOR [Discount_Pct]
GO
ALTER TABLE [dbo].[SO_Detail] ADD CONSTRAINT [DF_SO_Detail_Price_UofM] DEFAULT ('ea') FOR [Price_UofM]
GO
ALTER TABLE [dbo].[SO_Detail] ADD CONSTRAINT [DF_SO_Detail_Deferred_Qty] DEFAULT ((0)) FOR [Deferred_Qty]
GO
ALTER TABLE [dbo].[SO_Detail] ADD CONSTRAINT [DF_SO_Detail_Prepaid_Amt] DEFAULT ((0)) FOR [Prepaid_Amt]
GO
ALTER TABLE [dbo].[SO_Detail] ADD CONSTRAINT [DF_SO_Detail_Order_Qty] DEFAULT ((0)) FOR [Order_Qty]
GO
ALTER TABLE [dbo].[SO_Detail] ADD CONSTRAINT [DF_SO_Detail_Backorder_Qty] DEFAULT ((0)) FOR [Backorder_Qty]
GO
ALTER TABLE [dbo].[SO_Detail] ADD CONSTRAINT [DF_SO_Detail_Picked_Qty] DEFAULT ((0)) FOR [Picked_Qty]
GO
ALTER TABLE [dbo].[SO_Detail] ADD CONSTRAINT [DF_SO_Detail_Certs_Required] DEFAULT ((0)) FOR [Certs_Required]
GO
ALTER TABLE [dbo].[SO_Detail] ADD CONSTRAINT [DF_SO_Detail_Taxable] DEFAULT ((0)) FOR [Taxable]
GO
ALTER TABLE [dbo].[SO_Detail] ADD CONSTRAINT [DF_SO_Detail_Commissionable] DEFAULT ((0)) FOR [Commissionable]
GO
ALTER TABLE [dbo].[SO_Detail] ADD CONSTRAINT [DF_SO_Detail_Commission_Pct] DEFAULT ((0)) FOR [Commission_Pct]
GO
ALTER TABLE [dbo].[SO_Detail] ADD CONSTRAINT [DF_SO_Detail_Last_Updated] DEFAULT (getdate()) FOR [Last_Updated]
GO
ALTER TABLE [dbo].[SO_Detail] ADD CONSTRAINT [DF_SODetail_PriceUofM] DEFAULT ((1)) FOR [Price_Unit_Conv]
GO
ALTER TABLE [dbo].[SO_Detail] ADD DEFAULT ((0)) FOR [Prepaid_Trade_Amt]
GO
SO_HEADER
USE [PRODUCTION]
GO
/****** Object: Table [dbo].[SO_Header] Script Date: 05/06/2014 15:46:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[SO_Header](
[Sales_Order] [dbo].[Key10] NOT NULL,
[Customer] [dbo].[Key10] NOT NULL,
[Ship_To] [dbo].[KeyNum] NULL,
[Contact] [dbo].[KeyNum] NULL,
[Sales_Rep] [dbo].[Key6] NULL,
[Order_Taken_By] [dbo].[Key6] NULL,
[Ship_Via] [dbo].[T_UCode] NULL,
[Tax_Code] [dbo].[T_UCode] NULL,
[Terms] [dbo].[T_UCode] NULL,
[Sales_Tax_Amt] [money] NOT NULL,
[Sales_Tax_Rate] [float] NOT NULL,
[Order_Date] [datetime] NOT NULL,
[Promised_Date] [datetime] NULL,
[Customer_PO] [dbo].[T_20] NULL,
[Status] [dbo].[T_8] NOT NULL,
[Total_Price] [money] NOT NULL,
[Currency_Conv_Rate] [float] NOT NULL,
[Trade_Currency] [dbo].[KeyNum] NULL,
[Fixed_Rate] [bit] NOT NULL,
[Trade_Date] [datetime] NULL,
[Note_Text] [text] NULL,
[Comment] [text] NULL,
[Last_Updated] [datetime] NOT NULL,
[User_Values] [int] NULL,
[Source] [dbo].[T_20] NULL,
[Prepaid_Tax_Amount] [money] NULL,
CONSTRAINT [PK_SO_Header] PRIMARY KEY NONCLUSTERED
[Sales_Order] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
ALTER TABLE [dbo].[SO_Header] ADD CONSTRAINT [DF_SO_Header_Sales_Tax_Amt] DEFAULT ((0)) FOR [Sales_Tax_Amt]
GO
ALTER TABLE [dbo].[SO_Header] ADD CONSTRAINT [DF_SO_Header_Sales_Tax_Rate] DEFAULT ((0)) FOR [Sales_Tax_Rate]
GO
ALTER TABLE [dbo].[SO_Header] ADD CONSTRAINT [DF_SO_Header_Total_Price] DEFAULT ((0)) FOR [Total_Price]
GO
ALTER TABLE [dbo].[SO_Header] ADD CONSTRAINT [DF_SO_Header_Currency_Conv_Rate] DEFAULT ((1)) FOR [Currency_Conv_Rate]
GO
ALTER TABLE [dbo].[SO_Header] ADD CONSTRAINT [DF_SO_Header_Fixed_Rate] DEFAULT ((1)) FOR [Fixed_Rate]
GO
ALTER TABLE [dbo].[SO_Header] ADD CONSTRAINT [DF_SO_Header_Last_Updated] DEFAULT (getdate()) FOR [Last_Updated]
GO
ALTER TABLE [dbo].[SO_Header] ADD DEFAULT ((0)) FOR [Prepaid_Tax_Amount]
GO
MATERIAL
USE [PRODUCTION]
GO
/****** Object: Table [dbo].[Material] Script Date: 05/06/2014 15:47:31 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Material](
[Material] [dbo].[Key30] NOT NULL,
[Primary_Vendor] [dbo].[Key10] NULL,
[User_Values] [dbo].[KeyNum] NULL,
[Shape] [dbo].[Key10] NULL,
[Location_ID] [dbo].[Key10] NOT NULL,
[Sales_Code] [dbo].[T_15] NULL,
[Description] [dbo].[T_30] NULL,
[Type] [dbo].[T_1] NOT NULL,
[Status] [dbo].[T_8] NOT NULL,
[Pick_Buy_Indicator] [dbo].[T_1] NOT NULL,
[Class] [varchar](10) NULL,
[Rev] [dbo].[T_8] NULL,
[Stocked_UofM] [dbo].[UofM] NOT NULL,
[Purchase_UofM] [dbo].[UofM] NOT NULL,
[Cost_UofM] [dbo].[UofM] NOT NULL,
[Price_UofM] [dbo].[UofM] NOT NULL,
[Selling_Price] [float] NULL,
[Standard_Cost] [float] NOT NULL,
[Average_Cost] [float] NULL,
[Last_Cost] [float] NULL,
[On_Order_Qty] [float] NULL,
[Order_Point] [float] NULL,
[Reorder_Qty] [float] NOT NULL,
[Lead_Days] [smallint] NOT NULL,
[UofM_Conv_Factor] [float] NOT NULL,
[Lot_Trace] [bit] NOT NULL,
[Rd_Whole_Unit] [bit] NOT NULL,
[Ext_Description] [text] NULL,
[Make_Buy] [dbo].[T_1] NOT NULL,
[Vendor_Reference] [dbo].[T_30] NULL,
[Drawing] [varchar](30) NULL,
[Use_Price_Breaks] [bit] NOT NULL,
[Note_Text] [text] NULL,
[Last_Updated] [datetime] NOT NULL,
[GL_Account] [dbo].[T_100] NULL,
[Price_Unit_Conv] [float] NULL,
[Holder_ID] [dbo].[T_50] NULL,
[Job] [dbo].[T_10] NULL,
[Tax_Code] [dbo].[T_15] NULL,
[Taxable] [bit] NULL,
[IS_Length] [float] NULL,
[IS_Width] [float] NULL,
[IS_Weight_Factor] [float] NULL,
[IS_Thickness] [float] NULL,
[Stock_Item] [dbo].[T_50] NULL,
[Affects_Schedule] [bit] NULL,
[ObjectID] [uniqueidentifier] NOT NULL,
[Shape_OID] [uniqueidentifier] NULL,
[Tooling] [bit] NULL,
[IsSerialized] [bit] NOT NULL,
[MaxUsage] [int] NULL,
[ShelfLife] [float] NULL,
[ShelfLifeUofM] [varchar](10) NULL,
CONSTRAINT [PK_Material] PRIMARY KEY NONCLUSTERED
[Material] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
ALTER TABLE [dbo].[Material] WITH NOCHECK ADD CONSTRAINT [FK_Loc_on_Matl] FOREIGN KEY([Location_ID])
REFERENCES [dbo].[Location] ([Location_ID])
GO
ALTER TABLE [dbo].[Material] NOCHECK CONSTRAINT [FK_Loc_on_Matl]
GO
ALTER TABLE [dbo].[Material] WITH NOCHECK ADD CONSTRAINT [FK_Shap_on_Matl] FOREIGN KEY([Shape])
REFERENCES [dbo].[Shapes] ([Shape])
GO
ALTER TABLE [dbo].[Material] NOCHECK CONSTRAINT [FK_Shap_on_Matl]
GO
ALTER TABLE [dbo].[Material] WITH NOCHECK ADD CONSTRAINT [FK_UVal_on_Matl] FOREIGN KEY([User_Values])
REFERENCES [dbo].[User_Values] ([User_Values])
GO
ALTER TABLE [dbo].[Material] NOCHECK CONSTRAINT [FK_UVal_on_Matl]
GO
ALTER TABLE [dbo].[Material] WITH NOCHECK ADD CONSTRAINT [FK_Vend_on_Matl] FOREIGN KEY([Primary_Vendor])
REFERENCES [dbo].[Vendor] ([Vendor])
GO
ALTER TABLE [dbo].[Material] NOCHECK CONSTRAINT [FK_Vend_on_Matl]
GO
ALTER TABLE [dbo].[Material] ADD CONSTRAINT [DF_Material_Selling_Price] DEFAULT ((0)) FOR [Selling_Price]
GO
ALTER TABLE [dbo].[Material] ADD CONSTRAINT [DF_Material_Standard_Cost] DEFAULT ((0)) FOR [Standard_Cost]
GO
ALTER TABLE [dbo].[Material] ADD CONSTRAINT [DF_Material_Average_Cost] DEFAULT ((0)) FOR [Average_Cost]
GO
ALTER TABLE [dbo].[Material] ADD CONSTRAINT [DF_Material_Last_Cost] DEFAULT ((0)) FOR [Last_Cost]
GO
ALTER TABLE [dbo].[Material] ADD CONSTRAINT [DF_Material_On_Order_Qty] DEFAULT ((0)) FOR [On_Order_Qty]
GO
ALTER TABLE [dbo].[Material] ADD CONSTRAINT [DF_Material_Order_Point] DEFAULT ((0)) FOR [Order_Point]
GO
ALTER TABLE [dbo].[Material] ADD CONSTRAINT [DF_Material_Reorder_Qty] DEFAULT ((0)) FOR [Reorder_Qty]
GO
ALTER TABLE [dbo].[Material] ADD CONSTRAINT [DF_Material_Lead_Days] DEFAULT ((0)) FOR [Lead_Days]
GO
ALTER TABLE [dbo].[Material] ADD CONSTRAINT [DF_Material_UofM_Conv_Factor] DEFAULT ((0)) FOR [UofM_Conv_Factor]
GO
ALTER TABLE [dbo].[Material] ADD CONSTRAINT [DF_Material_Lot_Trace] DEFAULT ((0)) FOR [Lot_Trace]
GO
ALTER TABLE [dbo].[Material] ADD CONSTRAINT [DF_Material_Rd_Whole_Unit] DEFAULT ((0)) FOR [Rd_Whole_Unit]
GO
ALTER TABLE [dbo].[Material] ADD CONSTRAINT [DF_Material_Use_Price_Break] DEFAULT ((0)) FOR [Use_Price_Breaks]
GO
ALTER TABLE [dbo].[Material] ADD CONSTRAINT [DF_Material_Last_Updated] DEFAULT (getdate()) FOR [Last_Updated]
GO
ALTER TABLE [dbo].[Material] ADD CONSTRAINT [DF_Material_PriceUofM] DEFAULT ((1)) FOR [Price_Unit_Conv]
GO
ALTER TABLE [dbo].[Material] ADD DEFAULT ((0)) FOR [IsSerialized]
GO
ALTER TABLE [dbo].[Material] ADD DEFAULT ((0)) FOR [MaxUsage]
GO
ALTER TABLE [dbo].[Material] ADD DEFAULT ((0)) FOR [ShelfLife]
GO
JOB
USE [PRODUCTION]
GO
/****** Object: Table [dbo].[Job] Script Date: 05/06/2014 15:50:24 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Job](
[Job] [dbo].[Key10] NOT NULL,
[Sales_Rep] [dbo].[Key6] NULL,
[Customer] [dbo].[Key10] NULL,
[Ship_To] [dbo].[KeyNum] NULL,
[User_Values] [dbo].[KeyNum] NULL,
[Quote] [dbo].[Key10] NULL,
[Contact] [dbo].[KeyNum] NULL,
[Ship_Via] [dbo].[T_15] NULL,
[Terms] [dbo].[T_15] NULL,
[Tax_Code] [dbo].[T_15] NULL,
[Sales_Code] [dbo].[T_15] NULL,
[Top_Lvl_Job] [dbo].[T_10] NULL,
[Type] [dbo].[T_8] NOT NULL,
[Order_Date] [datetime] NOT NULL,
[Status] [dbo].[T_8] NOT NULL,
[Status_Date] [datetime] NOT NULL,
[Part_Number] [dbo].[T_30] NULL,
[Rev] [dbo].[T_10] NULL,
[Description] [dbo].[T_30] NULL,
[Ext_Description] [text] NULL,
[Drawing] [varchar](30) NULL,
[Build_To_Stock] [bit] NOT NULL,
[Order_Quantity] [int] NOT NULL,
[Extra_Quantity] [int] NULL,
[Pick_Quantity] [int] NULL,
[Make_Quantity] [int] NOT NULL,
[Split_Quantity] [int] NULL,
[Completed_Quantity] [int] NULL,
[Shipped_Quantity] [int] NULL,
[FG_Transfer_Qty] [int] NULL,
[Returned_Quantity] [int] NULL,
[In_Production_Quantity] [int] NOT NULL,
[Assembly_Level] [smallint] NULL,
[Certs_Required] [bit] NOT NULL,
[Time_And_Materials] [bit] NOT NULL,
[Open_Operations] [smallint] NULL,
[Scrap_Pct] [float] NOT NULL,
[Est_Scrap_Qty] [int] NULL,
[Est_Rem_Hrs] [float] NULL,
[Est_Total_Hrs] [float] NULL,
[Est_Labor] [money] NULL,
[Est_Material] [money] NULL,
[Est_Service] [money] NULL,
[Est_Labor_Burden] [money] NULL,
[Est_Machine_Burden] [money] NULL,
[Est_GA_Burden] [money] NULL,
[Act_Revenue] [money] NULL,
[Act_Scrap_Quantity] [int] NULL,
[Act_Total_Hrs] [float] NULL,
[Act_Labor] [money] NULL,
[Act_Material] [money] NULL,
[Act_Service] [money] NULL,
[Act_Labor_Burden] [money] NULL,
[Act_Machine_Burden] [money] NULL,
[Act_GA_Burden] [money] NULL,
[Priority] [smallint] NULL,
[Unit_Price] [float] NULL,
[Total_Price] [money] NULL,
[Price_UofM] [dbo].[T_4] NULL,
[Currency_Conv_Rate] [float] NOT NULL,
[Trade_Currency] [dbo].[KeyNum] NULL,
[Fixed_Rate] [bit] NOT NULL,
[Trade_Date] [datetime] NULL,
[Commission_Pct] [float] NULL,
[Customer_PO] [dbo].[T_20] NULL,
[Customer_PO_LN] [dbo].[T_6] NULL,
[Sched_End] [datetime] NULL,
[Sched_Start] [datetime] NULL,
[Quantity_Per] [float] NULL,
[Profit_Pct] [float] NULL,
[Labor_Markup_Pct] [float] NOT NULL,
[Mat_Markup_Pct] [float] NOT NULL,
[Serv_Markup_Pct] [float] NOT NULL,
[Labor_Burden_Markup_Pct] [float] NOT NULL,
[Machine_Burden_Markup_Pct] [float] NOT NULL,
[GA_Burden_Markup_Pct] [float] NOT NULL,
[Lead_Days] [smallint] NULL,
[Profit_Markup] [dbo].[T_1] NULL,
[Prepaid_Amt] [money] NULL,
[Split_To_Job] [bit] NOT NULL,
[Note_Text] [text] NULL,
[Comment] [text] NULL,
[Last_Updated] [datetime] NOT NULL,
[Order_Unit] [dbo].[T_4] NULL,
[Price_Unit_Conv] [float] NULL,
[Holder_ID] [dbo].[T_50] NULL,
[Source] [dbo].[T_20] NULL,
[Order_Taken_By] [dbo].[T_50] NULL,
[Plan_Modified] [bit] NULL,
[ObjectID] [uniqueidentifier] NOT NULL,
[Released_Date] [datetime] NULL,
[Prepaid_Tax_Amount] [money] NULL,
[Prepaid_Trade_Amt] [money] NULL,
[Last_Updated_By] [dbo].[T_50] NULL,
CONSTRAINT [PK_Job] PRIMARY KEY NONCLUSTERED
[Job] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
ALTER TABLE [dbo].[Job] WITH NOCHECK ADD CONSTRAINT [FK_Addr_on_Job] FOREIGN KEY([Ship_To])
REFERENCES [dbo].[Address] ([Address])
GO
ALTER TABLE [dbo].[Job] NOCHECK CONSTRAINT [FK_Addr_on_Job]
GO
ALTER TABLE [dbo].[Job] WITH NOCHECK ADD CONSTRAINT [FK_Cust_on_Job] FOREIGN KEY([Customer])
REFERENCES [dbo].[Customer] ([Customer])
GO
ALTER TABLE [dbo].[Job] NOCHECK CONSTRAINT [FK_Cust_on_Job]
GO
ALTER TABLE [dbo].[Job] WITH NOCHECK ADD CONSTRAINT [FK_Empl_on_Job] FOREIGN KEY([Sales_Rep])
REFERENCES [dbo].[Employee] ([Employee])
GO
ALTER TABLE [dbo].[Job] NOCHECK CONSTRAINT [FK_Empl_on_Job]
GO
ALTER TABLE [dbo].[Job] WITH NOCHECK ADD CONSTRAINT [FK_UVal_on_Job] FOREIGN KEY([User_Values])
REFERENCES [dbo].[User_Values] ([User_Values])
GO
ALTER TABLE [dbo].[Job] NOCHECK CONSTRAINT [FK_UVal_on_Job]
GO
ALTER TABLE [dbo].[Job] ADD CONSTRAINT [DF_Job_Build_To_Stock] DEFAULT ((0)) FOR [Build_To_Stock]
GO
ALTER TABLE [dbo].[Job] ADD CONSTRAINT [DF_Job_Order_Quantity] DEFAULT ((0)) FOR [Order_Quantity]
GO
ALTER TABLE [dbo].[Job] ADD CONSTRAINT [DF_Job_Extra_Quantity] DEFAULT ((0)) FOR [Extra_Quantity]
GO
ALTER TABLE [dbo].[Job] ADD CONSTRAINT [DF_Job_Pick_Quantity] DEFAULT ((0)) FOR [Pick_Quantity]
GO
ALTER TABLE [dbo].[Job] ADD CONSTRAINT [DF_Job_Make_Quantity] DEFAULT ((0)) FOR [Make_Quantity]
GO
ALTER TABLE [dbo].[Job] ADD CONSTRAINT [DF_Job_Split_Quantity] DEFAULT ((0)) FOR [Split_Quantity]
GO
ALTER TABLE [dbo].[Job] ADD CONSTRAINT [DF_Job_Completed_Quantity] DEFAULT ((0)) FOR [Completed_Quantity]
GO
ALTER TABLE [dbo].[Job] ADD CONSTRAINT [DF_Job_Shipped_Quantity] DEFAULT ((0)) FOR [Shipped_Quantity]
GO
ALTER TABLE [dbo].[Job] ADD CONSTRAINT [DF_Job_FG_Transfer_Qty] DEFAULT ((0)) FOR [FG_Transfer_Qty]
GO
ALTER TABLE [dbo].[Job] ADD CONSTRAINT [DF_Job_Returned_Quantity] DEFAULT ((0)) FOR [Returned_Quantity]
GO
ALTER TABLE [dbo].[Job] ADD CONSTRAINT [DF_Job_In_Production_Quantity] DEFAULT ((0)) FOR [In_Production_Quantity]
GO
ALTER TABLE [dbo].[Job] ADD CONSTRAINT [DF_Job_Assembly_Level] DEFAULT ((0)) FOR [Assembly_Level]
GO
ALTER TABLE [dbo].[Job] ADD CONSTRAINT [DF_Job_Certs_Required] DEFAULT ((0)) FOR [Certs_Required]
GO
ALTER TABLE [dbo].[Job] ADD CONSTRAINT [DF_Job_Time_And_Materials] DEFAULT ((0)) FOR [Time_And_Materials]
GO
ALTER TABLE [dbo].[Job] ADD CONSTRAINT [DF_Job_Open_Operations] DEFAULT ((0)) FOR [Open_Operations]
GO
ALTER TABLE [dbo].[Job] ADD CONSTRAINT [DF_Job_Scrap_Pct] DEFAULT ((0)) FOR [Scrap_Pct]
GO
ALTER TABLE [dbo].[Job] ADD CONSTRAINT [DF_Job_Est_Scrap_Qty] DEFAULT ((0)) FOR [Est_Scrap_Qty]
GO
ALTER TABLE [dbo].[Job] ADD CONSTRAINT [DF_Job_Est_Rem_Hrs] DEFAULT ((0)) FOR [Est_Rem_Hrs]
GO
ALTER TABLE [dbo].[Job] ADD CONSTRAINT [DF_Job_Est_Total_Hrs] DEFAULT ((0)) FOR [Est_Total_Hrs]
GO
ALTER TABLE [dbo].[Job] ADD CONSTRAINT [DF_Job_Est_Labor] DEFAULT ((0)) FOR [Est_Labor]
GO
ALTER TABLE [dbo].[Job] ADD CONSTRAINT [DF_Job_Est_Material] DEFAULT ((0)) FOR [Est_Material]
GO
ALTER TABLE [dbo].[Job] ADD CONSTRAINT [DF_Job_Est_Service] DEFAULT ((0)) FOR [Est_Service]
GO
ALTER TABLE [dbo].[Job] ADD CONSTRAINT [DF_Job_Est_Labor_Burden] DEFAULT ((0)) FOR [Est_Labor_Burden]
GO
ALTER TABLE [dbo].[Job] ADD CONSTRAINT [DF_Job_Est_Machine_Burden] DEFAULT ((0)) FOR [Est_Machine_Burden]
GO
ALTER TABLE [dbo].[Job] ADD CONSTRAINT [DF_Job_Est_GA_Burden] DEFAULT ((0)) FOR [Est_GA_Burden]
GO
ALTER TABLE [dbo].[Job] ADD CONSTRAINT [DF_Job_Act_Revenue] DEFAULT ((0)) FOR [Act_Revenue]
GO
ALTER TABLE [dbo].[Job] ADD CONSTRAINT [DF_Job_Act_Scrap_Quantity] DEFAULT ((0)) FOR [Act_Scrap_Quantity]
GO
ALTER TABLE [dbo].[Job] ADD CONSTRAINT [DF_Job_Act_Total_Hrs] DEFAULT ((0)) FOR [Act_Total_Hrs]
GO
ALTER TABLE [dbo].[Job] ADD CONSTRAINT [DF_Job_Act_Labor] DEFAULT ((0)) FOR [Act_Labor]
GO
ALTER TABLE [dbo].[Job] ADD CONSTRAINT [DF_Job_Act_Material] DEFAULT ((0)) FOR [Act_Material]
GO
ALTER TABLE [dbo].[Job] ADD CONSTRAINT [DF_Job_Act_Service] DEFAULT ((0)) FOR [Act_Service]
GO
ALTER TABLE [dbo].[Job] ADD CONSTRAINT [DF_Job_Act_Labor_Burden] DEFAULT ((0)) FOR [Act_Labor_Burden]
GO
ALTER TABLE [dbo].[Job] ADD CONSTRAINT [DF_Job_Act_Machine_Burden] DEFAULT ((0)) FOR [Act_Machine_Burden]
GO
ALTER TABLE [dbo].[Job] ADD CONSTRAINT [DF_Job_Act_GA_Burden] DEFAULT ((0)) FOR [Act_GA_Burden]
GO
ALTER TABLE [dbo].[Job] ADD CONSTRAINT [DF_Job_Priority] DEFAULT ((5)) FOR [Priority]
GO
ALTER TABLE [dbo].[Job] ADD CONSTRAINT [DF_Job_Unit_Price] DEFAULT ((0)) FOR [Unit_Price]
GO
ALTER TABLE [dbo].[Job] ADD CONSTRAINT [DF_Job_Total_Price] DEFAULT ((0)) FOR [Total_Price]
GO
ALTER TABLE [dbo].[Job] ADD CONSTRAINT [DF_Job_Currency_Conv_Rate] DEFAULT ((1)) FOR [Currency_Conv_Rate]
GO
ALTER TABLE [dbo].[Job] ADD CONSTRAINT [DF_Job_Fixed_Rate] DEFAULT ((1)) FOR [Fixed_Rate]
GO
ALTER TABLE [dbo].[Job] ADD CONSTRAINT [DF_Job_Commission_Pct] DEFAULT ((0)) FOR [Commission_Pct]
GO
ALTER TABLE [dbo].[Job] ADD CONSTRAINT [DF_Job_Quantity_Per] DEFAULT ((1)) FOR [Quantity_Per]
GO
ALTER TABLE [dbo].[Job] ADD CONSTRAINT [DF_Job_Profit_Pct] DEFAULT ((0)) FOR [Profit_Pct]
GO
ALTER TABLE [dbo].[Job] ADD CONSTRAINT [DF_Job_Labor_Markup_Pct] DEFAULT ((0)) FOR [Labor_Markup_Pct]
GO
ALTER TABLE [dbo].[Job] ADD CONSTRAINT [DF_Job_Mat_Markup_Pct] DEFAULT ((0)) FOR [Mat_Markup_Pct]
GO
ALTER TABLE [dbo].[Job] ADD CONSTRAINT [DF_Job_Serv_Markup_Pct] DEFAULT ((0)) FOR [Serv_Markup_Pct]
GO
ALTER TABLE [dbo].[Job] ADD CONSTRAINT [DF_Job_Labor_Burden_Markup_Pct] DEFAULT ((0)) FOR [Labor_Burden_Markup_Pct]
GO
ALTER TABLE [dbo].[Job] ADD CONSTRAINT [DF_Job_Machine_Burden_Markup_Pct] DEFAULT ((0)) FOR [Machine_Burden_Markup_Pct]
GO
ALTER TABLE [dbo].[Job] ADD CONSTRAINT [DF_Job_GA_Burden_Markup_Pct] DEFAULT ((0)) FOR [GA_Burden_Markup_Pct]
GO
ALTER TABLE [dbo].[Job] ADD CONSTRAINT [DF_Job_Lead_Days] DEFAULT ((0)) FOR [Lead_Days]
GO
ALTER TABLE [dbo].[Job] ADD CONSTRAINT [DF_Job_Prepaid_Amt] DEFAULT ((0)) FOR [Prepaid_Amt]
GO
ALTER TABLE [dbo].[Job] ADD CONSTRAINT [DF_Job_Split_To_Job] DEFAULT ((0)) FOR [Split_To_Job]
GO
ALTER TABLE [dbo].[Job] ADD CONSTRAINT [DF_Job_Last_Updated] DEFAULT (getdate()) FOR [Last_Updated]
GO
ALTER TABLE [dbo].[Job] ADD CONSTRAINT [DF_JOB_PriceUofM] DEFAULT ((1)) FOR [Price_Unit_Conv]
GO
ALTER TABLE [dbo].[Job] ADD DEFAULT ((0)) FOR [Prepaid_Tax_Amount]
GO
ALTER TABLE [dbo].[Job] ADD DEFAULT ((0)) FOR [Prepaid_Trade_Amt]
GO
SWProduction1.The best solution is not to use text, ntext, and image data types
If you can, it is highly rcommend to fix the tables structure
2. we can not use your DDL since it is not complete. Your table create query include data type that we dont have like:
CREATE TABLE [dbo].[SO_Detail](
[SO_DetailKey] [dbo].[KeyNum] IDENTITY(1,1) NOT NULL,...
Therefore we can not check your specific situation :-(
3. If you have to use text, ntext data types then
* Read this old blog (Not related to you corent problem but you should know this!): SQL Server support NTEXT/TEXT, but SSMS does not
http://ariely.info/Blog/tabid/83/EntryId/120/SQL-Server-support-NTEXT-TEXT-but-SSMS-does-not.aspx
* As v.vt wrote, Convert the data in the query from TEXT/NTEXT into VARCHAR/NVARCHAR and the query should work OK
[Personal Site] [Blog] [Facebook] -
Creation of object in universe to show the count in report
Hi,
I am trying to create an object in universe.
I had a table called projects in which there are projectid and managers and now i want to show in report as below.
15 PMu2019s assigned to 1-3 Projects
10 PMu2019s assigned to 4 Projects
20 PMu2019s assigned to > 5 Projects
The count of managers assigned to the number of projects. Could any one pls explain in detail how i can do this in universe.
Thanks,
EswarHi,
Here is the syntax:
SELECT CAST(SUM(a.nb_Mgr) AS VARCHAR) + ' Managers: 1-2 projects' as Nb_Mgr FROM
(SELECT Count(distinct Manager) as nb_Mgr from ISL.dbo.Projects group by Manager having count(Project) <= 2) a
UNION
SELECT CAST(SUM(a.nb_Mgr) AS VARCHAR) + ' Managers: 3-5 projects' FROM
(SELECT Count(distinct Manager) as nb_Mgr from ISL.dbo.Projects group by Manager having count(Project) > 2 and count(Project) <= 5) a
UNION
SELECT CAST(SUM(a.nb_Mgr) AS VARCHAR) + ' Managers: > 5 projects' FROM
(SELECT Count(distinct Manager) as nb_Mgr from ISL.dbo.Projects group by Manager having count(Project) > 5) a
By the way you can create a more sophisticated derived table that let users choosing tha values for the number of projects:
SELECT CAST(SUM(a.nb_Mgr) AS VARCHAR) + ' Managers < ' + @Prompt('Min threshold','A',,mono,free) + ' projects' as Nb_Mgr FROM
(SELECT Count(distinct Manager) as nb_Mgr from ISL.dbo.Projects group by Manager having count(Project) < @Prompt('Min threshold','N',,mono,free)) a
UNION
SELECT CAST(SUM(a.nb_Mgr) AS VARCHAR) + ' Managers between ' + @Prompt('Min threshold','A',,mono,free) + ' and ' + @Prompt('Max threshold','A',,mono,free) + ' projects' FROM
(SELECT Count(distinct Manager) as nb_Mgr from ISL.dbo.Projects group by Manager having count(Project) >= @Prompt('Min threshold','N',,mono,free) and count(Project) <= @Prompt('Max threshold','N',,mono,free)) a
UNION
SELECT CAST(SUM(a.nb_Mgr) AS VARCHAR) + ' Managers > ' + @Prompt('Max threshold','A',,mono,free) + ' projects' FROM
(SELECT Count(distinct Manager) as nb_Mgr from ISL.dbo.Projects group by Manager having count(Project) > @Prompt('Max threshold','N',,mono,free)) a
Regards
Didier -
Help Needed in Dynamic Sql or alternate to Dynamic Sql
Hi Am working in sqlserver 2008 R2 and here is my Table structure and SPC
;create table SalaryReport(IdSalary int primary key identity(1,1),
IDMainCompany int,IDSubCompany int,Salary money,Incentive int,NoofEmployees int, SalaryDate datetime, Creditscore int );
insert into SalaryReport (IDMainCompany,IDSubCompany,Salary,Incentive,NoofEmployees,SalaryDate,Creditscore)
( Select 100 as IDMainCompany , 1000 as IDSubCompany ,200000 AS Salary, 20000 as Incentive, 500 as NoofEmployees,
'2014-01-01' as SalaryDate, 60 as Creditscore union all
Select 100 as IDMainCompany , 1001 as IDSubCompany ,300000 AS Salary, 40000 as Incentive, 600 as NoofEmployees,
'2014-01-01' as SalaryDate , 70 as Creditscore union all
Select 100 as IDMainCompany , 1002 as IDSubCompany ,400000 AS Salary, 40000 as Incentive, 1500 as NoofEmployees,
'2014-01-01' as SalaryDate , 45 as Creditscore union all
Select 101 as IDMainCompany , 1003 as IDSubCompany ,30000 AS Salary, 2000 as Incentive, 100 as NoofEmployees,
'2014-01-01' as SalaryDate, 60 as Creditscore union all
Select 102 as IDMainCompany , 1004 as IDSubCompany ,450000 AS Salary, 25000 as Incentive, 700 as NoofEmployees,
'2014-01-01' as SalaryDate, 30 as Creditscore)
Sample Test Script:
DECLARE @IDMainCompany int = 100;
DECLARE @Process_Date datetime = '2014-01-01';
declare @Query nvarchar(max);
SELECT
CAST(SR.IDMainCompany AS VARCHAR(12)) AS IDMainCompany
,CAST(SR.IDSubCompany AS VARCHAR(12)) AS IDSubCompany
,CAST(SR.Salary AS VARCHAR(12)) AS Salary
,CAST(SR.Incentive AS VARCHAR(12)) AS Incentive
,CAST(SR.NoofEmployees AS VARCHAR(12)) AS NoofEmployees
,CAST(SR.SalaryDate AS VARCHAR(15)) AS SalaryDate
,CAST((SR.Creditscore) AS VARCHAR(15)) AS average
FROM SalaryReport SR
WHERE SR.IDMainCompany = @IDMainCompany
AND DATEPART(MM, SR.SalaryDate) = DATEPART(MM, @Process_Date)
UNION ALL
SELECT
'' AS IDMainCompany
,'' AS IDSubCompany
,'Total: ' + CAST(SUM(SR.Salary) AS VARCHAR(12)) AS Salary
,'Total: ' + CAST(SUM(SR.Incentive) AS VARCHAR(12)) AS Incentive
,'Total: ' + CAST(SUM(SR.NoofEmployees) AS VARCHAR(12)) AS NoofEmployees
,'' AS SalaryDate
,'Total: ' +CAST(avg(SR.Creditscore) AS VARCHAR(12)) AS Totalaverage
FROM SalaryReport SR
WHERE SR.IDMainCompany = @IDMainCompany
AND DATEPART(MM, SR.SalaryDate) = DATEPART(MM, @Process_Date)
group by IDMainCompany, DATEPART(MM, SalaryDate)
the sample data i posted is having less columns. actually i have 20 columns in the select list. Also the parameters to the where condition i gave two i.e IDMainCompany, SalaryDate. I will also need to use IDSubCompany for some case. My skeleton will be
Create Procedure Test(@IDMainCompany int, @IDSubCompany int = null, @SalaryDate datetime)
as
BEGIN
IF(@IDMainCompany is not null && @IDMainCompany > 0 && @SalaryDate is not null && @SalaryDate <> ' ' &&
@IDSubCompany is null)
BEGIN
--The logic what discussed on previous posts will falls here with @IDMainCompany, @SalaryDate as parameter to the where condition
END
IF(@IDMainCompany is not null && @IDMainCompany > 0 && @SalaryDate is not null && @SalaryDate <> ' ' &&
@IDSubCompany is null && @IDSubCompany > 0 )
BEGIN
--The logic what discussed on previous posts will falls here with @IDMainCompany, @SalaryDate,@IDSubCompany as parameter to the where condition
END
END
As said i need to include 20 columns in the select list and as union all used on the previous sample there are 20 columns on the first query and 20 columns on the second query after the union all. The SPC will become big. If i repeat this for second if condition,
it will be too big. How can i reduce this writing more lines.
I am aware of the concept dynamic sql. Is there any other way to do this? or if dynamic sql is the only option, can anyone help me rewriting this select statements as dynamic sql
Could anyone please assist me
loving dotnet>>
thanks for your reply and yes, i am invoking this from my asp.net application using C# language. Would you like to share something?
<<
Yes,
You can use client side dynamic sql. I'm not talking about concatenating strings. I'm talking about using Runtime Text Tamplates (preprocesed templates in Visual Studio 2010).
Add a new "Runtime Text Template" item to your VS project. Be "MyReportTemplate.tt" the file name of the runtime text template. The content of this file should be something like the following:
<#@ template language="C#" #>
<#@ assembly name="System.Core" #>
SELECT
-- part of your query goes here
-- the interesting part come next
FROM
SalaryReport SR
WHERE
SR.IDMainCompany = @IDMainCompany
<# if (IDSubCompany.HasValue && IDSubCompany.Value > 0) { #>
AND SR.IDSubCompany = @IDSubCompany
<# } #>
AND
DATEPART(MM, SR.SalaryDate) = DATEPART(MM, @Process_Date)
GROUP BY
IDMainCompany, DATEPART(MM, SalaryDate)
Add a new c# code file named MyReportTemplate.partial.cs closed to MyReportTemplate.tt with the following code:
public partial class MyReportTemplate
public int? IDSubCompany { get; set; }
Then, to execute the query you can write a code similar to the following:
public DataTable ExecuteReport(int mainCompanyId, int? subCompanyId, DateTime processDate )
using (var cn = CreateConnection())
using (var cmd = new SqlCommand())
using (var adapter = new SqlDataAdapter(cmd))
cmd.Connection = cn;
var template = new MyReportTemplate
IDSubCompany = subCompanyId
cmd.CommandText = template.TransformText();
cmd.Parameters.AddWithValue("@IDSubCompany", subCompanyId == null ? (object) DBNull.Value : subCompanyId.Value);
cmd.Parameters.AddWithValue("@IDMainCompany", mainCompanyId);
cmd.Parameters.AddWithValue("@Process_Date", processDate);
var table = new DataTable();
adapter.Fill(table);
return table;
EntityLite: A Lightweight, Database First, Micro ORM -
Displaying different sums in the same row based on date ranges
Say I had a table like this
DECLARE @t1 TABLE (RowId INT PRIMARY KEY IDENTITY(1,1), BusinessType VARCHAR(100), SalesPerson VARCHAR(100), Category VARCHAR(100), OrderAmount DECIMAL(10,2), OrderDate DATETIME )
Now I want to get a result that is grouped first by BusinessType, then SalesPerson and include derived columns that are sums based on different date ranges.
Month-to-date = from the start of the current month to today
Month-to-date previous year = from the start of the current month to today 1 year ago
DECLARE @today DATETIME
DECLARE @today_prev_year DATETIME
DECLARE @year_start DATETIME
DECLARE @year_prev_start DATETIME
DECLARE @month_start DATETIME
DECLARE @month_prev_start DATETIME
SET @today = GETDATE();
SET @today_prev_year = DATEADD(YEAR,-1,@today)
SET @year_start = CAST('01/01/' + CAST(DATEPART(YEAR,GETDATE()) AS VARCHAR(10)) AS DATETIME);
SET @year_prev_start = DATEADD(YEAR,-1,@year_start)
SET @month_start = DATEADD(month, DATEDIFF(month, 0, @today), 0); --gets the first of the current month
SET @month_prev_start = DATEADD(YEAR,-1,@month_start); --gets the first of the current month
SELECT t.BusinessType,t.SalesPerson,t.Category
SUM(CASE WHEN o.OrderDate > @month_start AND ac.DocumentDate < @today THEN o.OrderAmount ELSE 0 END) AS MTDActualAmount
SUM(CASE WHEN o.OrderDate > @month_prev_start AND ac.DocumentDate < @today_prev_year THEN o.OrderAmount ELSE 0 END) AS MTDPrevActualAmount
FROM @t1 t
Hope this is clear as to what Im trying to do. Im ultimately going to pull this into an SSRS report, so im wondering if I can do this different SUM values in the report and handle the grouping there.
Thoughts?Based on your example (with a group by added) it should work.
However, if you incorperated a calendar table (http://social.technet.microsoft.com/wiki/contents/articles/29260.tsql-calendar-functions-and-tables.aspx)
you could lose all those manually set parameters:
DECLARE @t1 TABLE (RowId INT PRIMARY KEY IDENTITY(1,1), BusinessType VARCHAR(100), SalesPerson VARCHAR(100), Category VARCHAR(100), OrderAmount DECIMAL(10,2), OrderDate DATETIME, DocumentDate DATETIME)
INSERT INTO @t1 (BusinessType, SalesPerson, Category, OrderAmount, OrderDate, DocumentDate) VALUES
('A','Joe','CatA',10,'2015-01-01','2015-01-01'),('A','Joe','CatB',10,'2015-01-02','2015-01-01'),('A','Joe','CatA',30,'2015-01-03','2015-01-04'),('A','Joe','CatB',40,'2015-01-04','2015-01-01'),('A','Joe','CatA',100,'2015-02-01','2015-02-01'),
('A','Joe','CatB',100,'2015-02-02','2015-02-01'),('A','Joe','CatA',300,'2015-02-03','2015-02-04'),('A','Joe','CatB',400,'2015-02-04','2015-02-01'),('A','Bob','CatA',1,'2015-01-01','2015-01-01'),('A','Bob','CatB',1,'2015-01-02','2015-01-01'),
('A','Bob','CatA',3,'2015-01-03','2015-01-04'),('A','Bob','CatB',4,'2015-01-04','2015-01-01'),('A','Bob','CatA',10,'2015-02-01','2015-02-01'),('A','Bob','CatB',10,'2015-02-02','2015-02-01'),('A','Bob','CatA',30,'2015-02-03','2015-02-04'),
('A','Bob','CatB',40,'2015-02-04','2015-02-01'),('B','Joe','CatA',10,'2015-01-01','2015-01-01'),('B','Joe','CatB',10,'2015-01-02','2015-01-01'),('B','Joe','CatB',40,'2015-01-04','2015-01-01'),
('B','Joe','CatA',100,'2015-02-01','2015-02-01'),('B','Joe','CatB',100,'2015-02-02','2015-02-01'),('B','Joe','CatA',300,'2015-02-03','2015-02-04')
SELECT t.BusinessType,t.SalesPerson,t.Category,
SUM(CASE WHEN OrderDate >= monthStart AND DocumentDate < today THEN OrderAmount ELSE 0 END) AS MTDActualAmount,
SUM(CASE WHEN OrderDate BETWEEN prevMonthStart AND prevMonthENd AND DocumentDate >= yearStart THEN OrderAmount ELSE 0 END) AS MTDPrevActualAmount
FROM @t1 t
INNER JOIN calendar c
ON today = CAST(CURRENT_TIMESTAMP AS DATE)
Group by t.BusinessType,t.SalesPerson,t.Category -
Problem in retreiving string 1020 using ms sql in BODI sql query
I am taking a column from ms sql using select statement in bodi like
$temp=sql('ds_stage',select x from table A where X>1);
print('[$temp]');
it is printing the value upto 1020 characters of my data,after that it is not showing the remaining data.
I tried printing the sql statement directly in print statement rather than assigning it to a variable,
I tried casting teh value in select statemet like cast(x as text) or varchar and more.. nothing works..
no change in the result.
is that problem with BODI ? same query give full 1500 characters in ms sql but it doesnt come in BODI
I do not understand the problem.
ThanksI assume from your message that you are attempting to
deploy your application into OC4J - you're probably
implicitly using the inbuilt OC4J if your using JSPs.
If so, try placing the jdbc jars into the <JDEVHOME>\lib directory
and referencing them from the j2ee\home\application.xml
file:
use lines like:
<library path="../../../lib/msbase.jar" />
regards, Karl -
Over the past several weeks we've been experiencing periodic
hangs of the ColdFusion service. We finally invested in SeeFusion
and found the problem, but aren't sure how to fix it
The code that hangs is a query of queries block. Basically we
are getting a result set from verity (~1000 rows), then getting a
result set from SQL server (~3000 rows), and joining the two with
the query of query statement. Everything will run fine for a few
hours, then that block of code will bog down. When I dumped the
threads during the error, everything gets hung like so:
"jrpp-255" runnable
at
coldfusion.sql.imq.rttExpr.guesstimateJavaType(rttExpr.java:439)
at
coldfusion.sql.imq.rttExpr.guesstimateJavaType(rttExpr.java:371)
at
coldfusion.sql.imq.imqTable.guessColumnType(imqTable.java:443)
at
coldfusion.sql.QueryTableMetaData.InferMetaDataTypes(QueryTableMetaData.java:350)
at coldfusion.sql.imq.TableList.validate(TableList.java:166)
at
coldfusion.sql.imq.rttSelectExprSpec.validate(rttSelectExprSpec.java:498)
at
coldfusion.sql.imq.rttSelectStmt.validate(rttSelectStmt.java:84)
at
coldfusion.sql.imq.jdbcStatement.fetchResult(jdbcStatement.java:538)
at
coldfusion.sql.imq.jdbcStatement.execute(jdbcStatement.java:131)
at coldfusion.sql.Executive.executeQuery(Executive.java:775)
at coldfusion.sql.SqlImpl.execute(SqlImpl.java:240)
at
coldfusion.tagext.sql.QueryTag.doEndTag(QueryTag.java:500)
at
cfauctionManagement2ecfc978963305$funcJOINAUCTIONSTOVERITY.runFunction(D:\inetpub\wwwroot \CustomTags\mysite\component\auctionManagement.cfc:137)
at coldfusion.runtime.UDFMethod.invoke(UDFMethod.java:344)
at
coldfusion.filter.SilentFilter.invoke(SilentFilter.java:47)
at
coldfusion.runtime.UDFMethod$ReturnTypeFilter.invoke(UDFMethod.java:290)
at
coldfusion.runtime.UDFMethod$ArgumentCollectionFilter.invoke(UDFMethod.java:254)
at
coldfusion.filter.FunctionAccessFilter.invoke(FunctionAccessFilter.java:56)
at
coldfusion.runtime.UDFMethod.runFilterChain(UDFMethod.java:207)
at coldfusion.runtime.UDFMethod.invoke(UDFMethod.java:366)
at
coldfusion.runtime.TemplateProxy.invoke(TemplateProxy.java:198)
at
coldfusion.runtime.TemplateProxy.invoke(TemplateProxy.java:157)
at coldfusion.runtime.CfJspPage._invoke(CfJspPage.java:1594)
at
coldfusion.tagext.lang.InvokeTag.doEndTag(InvokeTag.java:341)
at
cfact_search_auctions2ecfm1040202400._factor47(D:\inetpub\wwwroot\CustomTags\mysite\actio n\act_search_auctions.cfm:849)
at
cfact_search_auctions2ecfm1040202400.runPage(D:\inetpub\wwwroot\CustomTags\mysite\action\ act_search_auctions.cfm:1)
at coldfusion.runtime.CfJspPage.invoke(CfJspPage.java:152)
at
coldfusion.filter.CFVariablesScopeFilter.invoke(CFVariablesScopeFilter.java:63)
at
coldfusion.tagext.lang.ModuleTag.doStartTag(ModuleTag.java:255)
at
coldfusion.runtime.CfJspPage._emptyTcfTag(CfJspPage.java:1925)
at
cfindex2ecfm1952396859.runPage(D:\inetpub\wwwroot\mysite\cfml\auctions\index.cfm:18)
at coldfusion.runtime.CfJspPage.invoke(CfJspPage.java:152)
at
coldfusion.tagext.lang.IncludeTag.doStartTag(IncludeTag.java:349)
at
coldfusion.runtime.CfJspPage._emptyTag(CfJspPage.java:1915)
at
cflas2dvegas2dtimeshares2ecfm1477369516.runPage(D:\inetpub\wwwroot\mysite\cfml\las-vegas- timeshares.cfm:1)
at coldfusion.runtime.CfJspPage.invoke(CfJspPage.java:152)
at
coldfusion.tagext.lang.IncludeTag.doStartTag(IncludeTag.java:349)
at
coldfusion.filter.CfincludeFilter.invoke(CfincludeFilter.java:65)
...etc
I believe this means CF is trying to "guesstimate" the java
type of each column in the result set. We tried to work around that
by CASTing each column as a varchar, but we still have the same
issue.
If anyone has an idea what the problem could be, we'd really
appreciate any help. Also, if anyone can suggest a way to merge the
two result sets without using SQL, that would be great too. I've
already tried nested loops to manually build the final result set,
but that was taking up to 5 seconds to run.
Environment:
CFMX 7.0.2
Win2K
SQL Server 2K> We need more information than that to display a record,
so we select
> everything out of the database (which is fairly quick),
then JOIN that to the
> verity results (WHERE auctionID = KEY).
Right. And what do you need THOUSANDS of matches for, in one
hit, here?
And what do you need ALL those columns for, when dealing with
all these
thousands of rows. You've not really answered my question as
to "what's
the end result here?" What are you trying to achieve? I don't
mean what
you're doing to aggregate the data, but simply *why*? What is
the
requirement you have here to be engaging in this enterprise
in the first
place? Search screen? Stock control report? What?
Is there any way of optimising how much processing you're
doing?
If - say - you're doing a search results screen, you probably
don't need
1000s of results: you probably need 20. So just ask the DB
for 20: WHERE
id IN (#list of 20 IDs from Verity search results#)
If the user goes "NEXT >>", then grab the next 20
(cache the Verity query
somehow, rather than re-query it).
Obviously there's some heavy-lifting processing that might
need to process
the whole lot. Can this not be done in a sliding window of
results? Or
could you not pass the list of IDs from the Verity resultset
into the DB
somehow, and do the filtering on the DB engine, rather than
with CF (which
is not very good at bulk data processing, as you're seeing.
It's not what
it's designed for).
I find QoQ to be very flaky for all ut the most basic
operations. For
basic stuff it's fine. It does not surprise me that it seems
to leak
memory (or whatever it's doing) and eventually give up the
ghost. This
does not help you, I realise, but as a suggested practice:
don't expect too
much out of QoQ. Try some other method instead.
Adam -
Purchasing Report Errors - Please Help
Hey everyone!
I am an SAP newb so bear with me please. I am having issues with a the Purchasing report on our system.
The report takes parameters determining the time period for which the report is to be run, ex: from Jan 1 2008 - Aug 1 2008.
The values returned by the report are:
Item code
Vendor
Item Name
Purch Unit
Available units
Units on Order (how many are currently dedicated to an already placed order)
Purchase Factor
Purchase Price
Purchase Currency
Avg Price
Price
Stock Value
MonthToDate Sales (calculates total sales for item within time period)
Average Sales (calculates the average sale for item within time period)
Sales Factor
Month on Order
Month on Stock
The Problems are occuring with: Month to Date Sales and Average Sales. As well as Month on Order and Month on Stock, however these are secondary.
The report in SAP is as follows:
BEGIN
declare @FrmWhs varchar(8),
@ToWhs varchar(8),
@WhsLst varchar(254),
@GroupCode int,
@FrmItm varchar(20),
@ToItm varchar(20),
@MthAgo int,
@GroupName varchar(20),
@HistStart varchar(6),
@HistEnd varchar(6),
@ShowInactive varchar(1)
SELECT @FrmWhs = T0.U_FrmWhs,
@ToWhs = T0.U_ToWhs,
@WhsLst = T0.U_WhsLst,
@GroupCode = T1.ItmsGrpCod,
@FrmItm = T0.U_FrmItm,
@ToItm = T0.U_ToItm,
@MthAgo = T0.U_MthAgo,
@HistStart = T0.U_Hist1,
@HistEnd = T0.U_Hist2,
@ShowInactive = T0.U_Inact
FROM dbo.@XXPURCH T0, dbo.OITB T1
WHERE T0.U_FrmWhs = '%0'
AND T0.U_ToWhs = '%1'
AND T0.U_WhsLst = '%2'
AND T1.ItmsGrpNam = '%3'
AND T1.Locked = 'X'
AND T0.U_FrmItm = '%4'
AND T0.U_ToItm = '%5'
AND T0.U_MthAgo = %6
AND T0.U_Hist1 = '%7'
AND T0.U_Hist2 = '%8'
AND T0.U_Inact = '%9'
SET @GroupName = '%3'
IF @GroupName = ''
SET @GroupCode = 0
ELSE
SELECT @GroupCode = T2.ItmsGrpCod
FROM dbo.OITB T2
WHERE T2.ItmsGrpNam = @GroupName
SET @FrmWhs = '%0'
SET @ToWhs = '%1'
SET @WhsLst = '%2'
SET @FrmItm = '%4'
SET @ToItm = '%5'
SET @MthAgo = %6
SET @HistStart = '%7'
SET @HistEnd = '%8'
SET @ShowInactive = '%9'
exec dbo.xxPurchReport @FrmWhs,@ToWhs,@WhsLst,@GroupCode,@FrmItm,@ToItm,@MthAgo,@HistStart,@HistEnd,@ShowInactive
I do not fully understand how the SQL query (the stored procedure) dbo.xxPurchasing Report calculates these numbers. If it is helpful, I could post the SQL query in its entirety or in part.
Thank you very much for your willingness to help. It is quite frustrating for me and it is so great to have knowledgeable people here to help
-HarrisonThanks. That makes sense.
I am not a database guy, but from my limited knowledge, so here is the query in its entirety:
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO
ALTER proc xxPurchReport (
@FromWhs varchar(8) = null,
@ToWhs varchar(8) = null,
@WhsList varchar(255) = null,
@GroupCode int = null,
@FromItem varchar(20) = null,
@ToItem varchar(20) = null,
@MonthsAgo int = 1,
@HistStart varchar(6) = null,
@HistEnd varchar(6) = null,
@ShowInactive char(1) = 'Y')
AS
begin
set NOCOUNT ON
DECLARE @StartDate datetime,
@EndDate datetime,
@Today datetime,
@Periods int
CREATE TABLE #tempwhs(WhsCode varchar(8))
if @WhsList is null or LTRIM(RTRIM(@WhsList)) = ''
BEGIN
if @FromWhs is null
set @FromWhs = ''
if @ToWhs is null or LTRIM(RTRIM(@ToWhs)) = ''
set @ToWhs = 'ZZZZZZZZ'
insert into #tempwhs
select WhsCode
from OWHS
where WhsCode between @FromWhs and @ToWhs
END
ELSE
BEGIN
set @WhsList = ',' + @WhsList + ','
insert into #tempwhs
select WhsCode
from OWHS
where charindex(',' + WhsCode + ',',@WhsList) > 0
END
if @GroupCode = 0
set @GroupCode = null
if @FromItem is null
set @FromItem = ''
if @ToItem is null or LTRIM(RTRIM(@ToItem)) = ''
set @ToItem = 'ZZZZZZZZZZZZZZZZZZZZ'
if @MonthsAgo is null
set @MonthsAgo = 0
if @MonthsAgo > 0
set @MonthsAgo = @MonthsAgo * -1
select @StartDate = dateadd(mm,@MonthsAgo,cast(cast(year(getdate()) as varchar(4)) + right(cast(month(getdate()) + 100 as varchar(3)),2) + '01' as datetime)),
@EndDate = dateadd(mi,-1,dateadd(mm,@MonthsAgo,dateadd(mm,1,cast(cast(year(getdate()) as varchar(4)) + right(cast(month(getdate()) + 100 as varchar(3)),2) + '01' as datetime)))),
@Today = cast(convert(varchar(8),getdate(),112) as datetime)
if isnull(@HistStart,'') = '' or isnull(@HistEnd,'') = ''
select @HistEnd = left(convert(varchar(8),@StartDate - 1,112),6),
@HistStart = left(convert(varchar(8),dateadd(yyyy,-1,@StartDate),112),6)
select @Periods = count(distinct period)
from XXSalesHistory
where period between @HistStart and @HistEnd
select itemcode,whscode,cast(round(cast(sum(totsale) as decimal(12,5)) / @Periods,2) as decimal(12,5)) as AvgSale,
cast(round(cast(sum(totqty) as decimal(12,5)) / @Periods,0) as int) as AvgQty
into #tmpavg
from XXSalesHistory
where period between @HistStart and @HistEnd
group by itemcode,whscode
order by 1
Select ItmGrp.ItmsGrpNam,lines.ItemCode,lines.WhsCode,
items.CardCode as DefaultVendor,items.ItemName,
whs.OnHand,items.SalUnitMsr as SaleUnit,items.BuyUnitMsr as PurchUnit,whs.IsCommited,
(whs.OnHand - whs.IsCommited) as Available,whs.OnOrder,items.PurFactor2,
isnull(purprc.Price,0) as PurchasePrice,
isnull(purprc.Currency,'USD') as PurchCurrency,
cast(whs.OnHand / (CASE WHEN items.PurFactor2 = 0 THEN 1 ELSE items.PurFactor2 END) as decimal(16,2)) as CS,
whs.AvgPrice,prc.Price,isnull(prc.Currency,'USD') as Currency,isnull(whs.StockValue,0) as StockValue,
cast(sum(case lines.usebaseun
when 'Y' then Lines.OpenCreQty
else ( Lines.OpenCreQty * Items.NumInSale) end) as integer) as MtdSales,
isnull(hst.AvgQty,0) as AvgSales,items.SalFactor2
into #temprpt
From OINV Main,
INV1 Lines,
OITM Items,
OITB ItmGrp,
OITW whs
left outer join #tmpavg hst
on hst.ItemCode = whs.ItemCode and hst.WhsCode = whs.WhsCode,
ITM1 prc,
ITM1 purprc
Where Main.DocDate between @StartDate and @EndDate
And Main.Instance = 0
And Main.Canceled = 'N'
and Main.DocEntry = Lines.DocEntry and lines.LineTotal <> 0
and lines.ItemCode between @FromItem and @ToItem
and lines.whscode collate database_default in (select WhsCode from #tempwhs)
and Items.ItemCode = Lines.ItemCode
and items.PrchseItem = 'Y'
and (@ShowInactive = 'Y' or Items.frozenfor = 'N')
and ItmGrp.ItmsGrpCod = Items.ItmsGrpCod
and ItmGrp.ItmsGrpCod = isnull(@GroupCode,ItmGrp.ItmsGrpCod)
and whs.ItemCode = lines.ItemCode and whs.WhsCode = lines.WhsCode
and prc.ItemCode = items.Itemcode
and prc.PriceList = (CASE WHEN whs.whscode = '02' THEN 6 else 2 END)
and purprc.ItemCode = items.Itemcode
and purprc.PriceList = (CASE WHEN whs.whscode = '02' THEN 10 else 1 END)
Group BY
ItmGrp.ItmsGrpNam,lines.ItemCode,lines.WhsCode,
items.CardCode,items.ItemName,
whs.OnHand,items.SalUnitMsr,items.BuyUnitMsr,whs.IsCommited,whs.OnOrder,items.PurFactor2,purprc.Price,isnull(purprc.Currency,'USD'),
cast(whs.OnHand / (CASE WHEN items.PurFactor2 = 0 THEN 1 ELSE items.PurFactor2 END) as decimal(16,2)),
whs.AvgPrice,prc.Price,prc.Currency,isnull(whs.StockValue,0),hst.AvgQty,items.SalFactor2
union
select grp.ItmsGrpNam,itm.ItemCode,whs.WhsCode,itm.CardCode as DefaultVendor,
itm.ItemName,whs.OnHand,itm.SalUnitMsr as SaleUnit,itm.BuyUnitMsr as PurchUnit,
whs.IsCommited,
(whs.OnHand - whs.IsCommited) as Available,whs.OnOrder,itm.PurFactor2,purprc.Price,
isnull(purprc.Currency,'USD') as PurchCurrency,
cast(whs.OnHand / (CASE WHEN itm.PurFactor2 = 0 THEN 1 ELSE itm.PurFactor2 END) as decimal(16,2)) as CS,
whs.AvgPrice,prc.Price,isnull(prc.Currency,'USD') as Currency,isnull(whs.StockValue,0) as StockValue,0,
isnull(hst.AvgQty,0) as AvgSales,itm.SalFactor2
from OITM itm,
OITB grp,
OITW whs
left join(INV1 lines inner join OINV main
on lines.DocEntry = main.DocEntry and lines.LineTotal <> 0
and main.Canceled = 'N' and main.instance = 0
and Main.DocDate Between @StartDate and @EndDate)
on whs.ItemCode = lines.ItemCode and whs.WhsCode = lines.WhsCode
left outer join #tmpavg hst on hst.ItemCode = whs.ItemCode and hst.WhsCode = whs.WhsCode,
ITM1 prc,
ITM1 purprc
where itm.ItemCode between @FromItem and @ToItem
and itm.PrchseItem = 'Y'
and (@ShowInactive = 'Y' or itm.frozenfor = 'N')
and grp.ItmsGrpCod = itm.ItmsGrpCod
and grp.ItmsGrpCod = isnull(@GroupCode,grp.ItmsGrpCod)
and whs.ItemCode = itm.ItemCode
and whs.WhsCode collate database_default in (select WhsCode from #tempwhs)
and main.DocEntry is null
and prc.ItemCode = itm.Itemcode
and prc.PriceList = (CASE WHEN whs.whscode = '02' THEN 6 else 2 END)
and purprc.ItemCode = itm.Itemcode
and purprc.PriceList = (CASE WHEN whs.whscode = '02' THEN 10 else 1 END)
group by grp.ItmsGrpNam,itm.ItemCode,whs.WhsCode,itm.CardCode,
itm.ItemName,whs.OnHand,itm.SalUnitMsr,itm.BuyUnitMsr,whs.IsCommited,whs.OnOrder,itm.PurFactor2,itm.LastPurPrc,purprc.Price,purprc.Currency,
cast(whs.OnHand / (CASE WHEN itm.PurFactor2 = 0 THEN 1 ELSE itm.PurFactor2 END) as decimal(16,2)),
whs.AvgPrice,prc.Price,prc.Currency,isnull(whs.StockValue,0),hst.AvgQty,itm.SalFactor2
select r.*,
cast((CASE WHEN r.OnOrder = 0
THEN 0
ELSE (CASE WHEN r.AvgSales = 0
THEN (CASE WHEN r.MtdSales = 0 THEN 999 ELSE r.OnOrder / r.MtdSales END)
ELSE r.OnOrder / r.AvgSales
END)
END) as decimal(9,1)) as MonthsOnOrder,
cast((CASE WHEN r.Available <= 0 THEN 0
ELSE (CASE WHEN r.AvgSales <= 0 THEN 999
ELSE r.Available / r.AvgSales END) END) as decimal(9,1)) as MonthsInStock
from #temprpt r
order by 1,2,3
end
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
I hope that is not too overwhelming, it is for me so any help you have to offer is truly appreciated. I am not trained in SAP but they have no one else. Thanks alot everyone! -
SSIS - Using Variables in Execute SQL Task Error
The following query in my Execute SQL Task throws the following error when run - [Execute SQL Task] Error: Executing the query "SELECT @columnz = COALESCE(@columnz + ',[' + times..." failed with the following error:
"Must declare the scalar variable "@columnz".". Possible failure reasons: Problems with the query,
"ResultSet" property not set correctly, parameters not set correctly, or connection not established correctly.
Query:
drop table tmpNCPCNCDownstreamMaxUtilization3wks
select node, max(utilization) as max_Utilization, DATE
into tmpNCPCNCDownstreamMaxUtilization3wks
from stage_ncpcncdownstream_temporal
WHERE Date BETWEEN DATEADD(day, -20, GETDATE()) AND GETDATE()
group by node, date
order by node
go
alter table tmpNCPCNCDownstreamMaxUtilization3wks add Timestamp varchar(50)
go
update tmpNCPCNCDownstreamMaxUtilization3wks
set Timestamp = 'WeekOf_' + cast(left(Date, 11) as varchar)
go
--drop table tmpNCPCNC_DownstreamNodeUtilizationMaxPivot
--go
declare @columnz varchar (8000)
go
SELECT @columnz = COALESCE(@columnz + ',[' + timestamp + ']','[' + timestamp+ ']')
FROM tmpNCPCNCDownstreamMaxUtilization3wks group by timestamp order by timestamp
go
--pivot contents in @columns
declare @query varchar(8000)
SET @query ='select * into tmpNCPCNC_DownstreamNodeUtilizationMaxPivot from
(select node, timestamp, Max_Utilization from tmpNCPCNCDownstreamMaxUtilization3wks)a
pivot
sum(max_Utilization) for timestamp in('+ @columnz +')
)as p'
execute (@query)
--empty contents from NCPCNCDownstreamMaxUtilization3wks
update tmpNCPCNCDownstreamMaxUtilization3wks
set timestamp =''
truncate table tmpNCPCNC_MaxDownstreamNodeUtilzationChart3Week
--load to table to be joined to Node feature class
insert into tmpNCPCNC_MaxDownstreamNodeUtilzationChart3Week
(Node, TwoWeeksAgo, PreviousWeek, CurrentWeek)
select * from tmpNCPCNC_DownstreamNodeUtilizationMaxPivot
--calculate average utilization for all values in each record
update tmpNCPCNC_MaxDownstreamNodeUtilzationChart3Week
set average = (coalesce(twoweeksago, 0) + coalesce(previousweek, 0) + coalesce(currentweek, 0))/3
from tmpNCPCNC_MaxDownstreamNodeUtilzationChart3Week
ScottIssue is with variable @columnz.
Scope of variables is only limited to the batch and if batch is over Variable is no more accessible.
Reproduce Steps:
DECLARE @columnz int = 0
Go --Scope of @columnz ends here
SELECT @columnz -- Ends up with error
So you have to remove GO keyword. I have commented 2 of them in below:
DROP TABLE tmpNCPCNCDownstreamMaxUtilization3wks
SELECT node
,max(utilization) AS max_Utilization
,DATE
INTO tmpNCPCNCDownstreamMaxUtilization3wks
FROM stage_ncpcncdownstream_temporal
WHERE DATE BETWEEN DATEADD(day, - 20, GETDATE())
AND GETDATE()
GROUP BY node
,DATE
ORDER BY node
GO
ALTER TABLE tmpNCPCNCDownstreamMaxUtilization3wks ADD TIMESTAMP VARCHAR(50)
GO
UPDATE tmpNCPCNCDownstreamMaxUtilization3wks
SET TIMESTAMP = 'WeekOf_' + cast(left(DATE, 11) AS VARCHAR)
GO
--drop table tmpNCPCNC_DownstreamNodeUtilizationMaxPivot
--go
DECLARE @columnz VARCHAR(8000)
--GO
SELECT @columnz = COALESCE(@columnz + ',[' + TIMESTAMP + ']', '[' + TIMESTAMP + ']')
FROM tmpNCPCNCDownstreamMaxUtilization3wks
GROUP BY TIMESTAMP
ORDER BY TIMESTAMP
--GO
--pivot contents in @columns
DECLARE @query VARCHAR(8000)
SET @query = 'select * into tmpNCPCNC_DownstreamNodeUtilizationMaxPivot from
(select node, timestamp, Max_Utilization from tmpNCPCNCDownstreamMaxUtilization3wks)a
pivot
sum(max_Utilization) for timestamp in(' + @columnz + ')
)as p'
EXECUTE (@query)
--empty contents from NCPCNCDownstreamMaxUtilization3wks
UPDATE tmpNCPCNCDownstreamMaxUtilization3wks
SET TIMESTAMP = ''
TRUNCATE TABLE tmpNCPCNC_MaxDownstreamNodeUtilzationChart3Week
--load to table to be joined to Node feature class
INSERT INTO tmpNCPCNC_MaxDownstreamNodeUtilzationChart3Week (
Node
,TwoWeeksAgo
,PreviousWeek
,CurrentWeek
SELECT *
FROM tmpNCPCNC_DownstreamNodeUtilizationMaxPivot
--calculate average utilization for all values in each record
UPDATE tmpNCPCNC_MaxDownstreamNodeUtilzationChart3Week
SET average = (coalesce(twoweeksago, 0) + coalesce(previousweek, 0) + coalesce(currentweek, 0)) / 3
FROM tmpNCPCNC_MaxDownstreamNodeUtilzationChart3Week
-Vaibhav Chaudhari -
Hi,
I have table called Employe. And the Columns are Emp_ID,EMP_NAME,SRC_SYS_CD,DOB
I have Query like
Select
COALESCE(MAX(CASE WHEN src_sys_cd='1' THEN Emp_id END), MAX(CASE WHEN src_sys_cd='2' THEN Emp_Id END))Emp_Id,
COALESCE(MAX(CASE WHEN src_sys_cd='1' THEN Emp_name END), MAX(CASE WHEN src_sys_cd='2' THEN Emp_Name END))Emp_name,
COALESCE(MAX(CASE WHEN src_sys_cd='1' THEN dob END), MAX(CASE WHEN src_sys_cd='2' THEN dob END))dob ,
from Employe
group by dob.
I want to generalize the query like get the columns from SYS.ALL_COLUMNS table for that table name and want to pass it to COALEACE() function. I tried with Cursor. But i didnt get the appropriate results.
Is there any way to achieve this? Please help me out in this regard.
Thanks,Is this the kinda thing you're after?
Add a filter to the queries to get just a single table/
WITH allCols AS (
SELECT s.name as sName, o.name AS oName, c.name AS cName, column_id,
CASE WHEN st.name in ('float','bigint','tinyint','int','smallint','bit','datetime','money','date','datetime2','uniqueidentifier','sysname','geography','geometry') THEN st.name
WHEN st.name in ('numeric','real') THEN st.name + '('+CAST(c.scale AS VARCHAR)+','+CAST(c.precision AS VARCHAR)+')'
WHEN st.name in ('varbinary','varchar','binary','char','nchar','nvarchar') THEN st.name + '(' + CAST(ABS(c.max_length) AS VARCHAR) + ')'
ELSE st.name + ' unknown '
END + ' '+
CASE WHEN c.is_identity = 1 THEN 'IDENTITY ' ELSE '' END +
CASE WHEN c.is_nullable = 0 THEN 'NOT ' ELSE '' END + 'NULL' AS bText,
f.name AS fileGroupName
FROM sys.columns c
INNER JOIN sys.objects o
ON c.object_id = o.object_id
AND o.type = 'U'
INNER JOIN sys.systypes st
ON c.user_type_id = st.xusertype
INNER JOIN sys.schemas s
ON o.schema_id = s.schema_id
INNER JOIN sys.indexes i
ON o.object_id = i.object_id
AND i.index_id = (SELECT MIN(index_id) FROM sys.indexes WHERE object_ID = o.object_id)
INNER JOIN sys.filegroups f
ON i.data_space_id = f.data_space_id
), rCTE AS (
SELECT sName, oName, cName, column_id, CAST(cName + ' ' + bText AS VARCHAR(MAX)) as bText, CAST(cName AS VARCHAR(MAX)) AS colList, fileGroupName
FROM allCols
WHERE column_id = 1
UNION ALL
SELECT r.sName, r.oName, r.cName, c.column_id, CAST(r.bText +', ' + c.cName + ' ' +c.bText AS VARCHAR(MAX)), CAST(r.colList+ ', ' +c.cName AS VARCHAR(MAX)), c.fileGroupName
FROM allCols c
INNER JOIN rCTE r
ON c.oName = r.oName
AND c.column_id - 1 = r.column_id
), allIndx AS (
SELECT 'CREATE '+CASE WHEN is_unique = 1 THEN ' UNIQUE ' ELSE '' END+i.type_desc+' INDEX ['+i.name+'] ON ['+CAST(s.name COLLATE DATABASE_DEFAULT AS NVARCHAR )+'].['+o.name+'] (' as prefix,
CASE WHEN is_included_column = 0 THEN '['+c.name+'] '+CASE WHEN ic.is_descending_key = 1 THEN 'DESC' ELSE 'ASC' END END As cols,
CASE WHEN is_included_column = 1 THEN '['+c.name+']'END As incCols,
') WITH ('+
CASE WHEN is_padded = 0 THEN 'PAD_INDEX = OFF,' ELSE 'PAD_INDEX = ON,' END+
CASE WHEN ignore_dup_key = 0 THEN 'IGNORE_DUP_KEY = OFF,' ELSE 'IGNORE_DUP_KEY = ON,' END+
CASE WHEN allow_row_locks = 0 THEN 'ALLOW_ROW_LOCKS = OFF,' ELSE 'ALLOW_ROW_LOCKS = ON,' END+
CASE WHEN allow_page_locks = 0 THEN 'ALLOW_PAGE_LOCKS = OFF' ELSE 'ALLOW_PAGE_LOCKS = ON' END+
')' as suffix, index_column_id, key_ordinal, f.name as fileGroupName
FROM sys.indexes i
LEFT OUTER JOIN sys.index_columns ic
ON i.object_id = ic.object_id
AND i.index_id = ic.index_id
LEFT OUTER JOIN sys.columns c
ON ic.object_id = c.object_id
AND ic.column_id = c.column_id
INNER JOIN sys.objects o
ON i.object_id = o.object_id
AND o.type = 'U'
AND i.type <> 0
INNER JOIN sys.schemas s
ON o.schema_id = s.schema_id
INNER JOIN sys.filegroups f
ON i.data_space_id = f.data_space_id
), idxrCTE AS (
SELECT r.prefix, CAST(r.cols AS NVARCHAR(MAX)) AS cols, CAST(r.incCols AS NVARCHAR(MAX)) AS incCols, r.suffix, r.index_column_id, r.key_ordinal, fileGroupName
FROM allIndx r
WHERE index_column_id = 1
UNION ALL
SELECT o.prefix, COALESCE(r.cols,'') + COALESCE(', '+o.cols,''), COALESCE(r.incCols+', ','') + o.incCols, o.suffix, o.index_column_id, o.key_ordinal, o.fileGroupName
FROM allIndx o
INNER JOIN idxrCTE r
ON o.prefix = r.prefix
AND o.index_column_id - 1 = r.index_column_id
SELECT 'CREATE TABLE ['+sName+'].[' + oName + '] ('+bText+') ON [' + fileGroupName +']'
FROM rCTE r
WHERE column_id = (SELECT MAX(column_id) FROM rCTE WHERE r.oName = oName)
UNION ALL
SELECT prefix + cols + CASE WHEN incCols IS NOT NULL THEN ') INCLUDE ('+incCols ELSE '' END + suffix+' ON [' + fileGroupName +']'
FROM idxrCTE x
WHERE index_column_id = (SELECT MAX(index_column_id) FROM idxrCTE WHERE x.prefix = prefix)
Maybe you are looking for
-
I just do the steps to authorize my computer but not become anything, why?
I just do the steps to authorize my computer but not become anything, why?
-
Context lookup failed "oracleasjms/esbdeferredtopic not found"
Hi, I've a problem when i deployed my ESB project to Test Server. I'm not using this TopicFactrory in my source code however when I use ANT script to generate the deployment plan, there is configuration for this factory as follow <deferredQueueName t
-
Photoshop crashes when batching images
Received an Event 1000 application error with the following event logs Exception code: 0xc0000005 Fault offset: 0x0000000000441382 Faulting process id: 0x1500 Faulting application start time: 0x01d0839d172b4dba Faulting application path: C:\Program F
-
I have tried several times to respond to your email with no luck. I did not have my new phone until march 2013 so why would I have a rebate for it in January 2013. no rebate, no papers in January or since. I did not even have my current phone number
-
Does the AEBS have a firewall?
I know you can set up the firewall on your mac, but I see not such options to set up in AEBS. I have set up password WPA2 Personal on the AEBS, but wasn't sure if there was anything else. In the Mac os firewall, you can set to stealth. Can you do tha