Search this insane blog:

Wednesday, September 1, 2010

Rolling up values (123A…123C..123D)

I have a task to roll certain  numbers up what have an ID with a letter at the end.

something like this:

  • 194A
    194B


  • 50A
    50D

I need to  ‘roll’ values (ie: Sales Amount, Quantities) regardless of the version (A..B..C..)

Here is some sample code that will help create some sample data:

create a fake table called blah:

if object_id('blah') is not null drop table blah
if object_id('blah') is null  create table blah (id int primary key identity, mixed_charachters varchar(20))

Now, insert values into that table:

insert  into blah (mixed_charachters)
        select  mixed_charachters
        from    (select '8B' as mixed_charachters union               
                 select '244'                  union
                 select '51B'                  union
                 select '172'                  union
                 select '247A'                  union
                 select '274'                  union
                 select '249'                  union
                 select '273'                  union
                 select '194B'                  union
                 select '198'                  union
                 select '271'                  union
                 select '50A'                  union
                 select '276C'                  union
                 select '254'                  union
                 select '115'                  union
                 select '93'                  union
                 select '158'                  union
                 select '210C'                  union
                 select '50D'                  union
                 select '102'                  union
                 select '265'                  union
                 select '250'                  union
                 select '51A'                  union
                 select '196'                  union
                 select '188'                  union
                 select '216E'                  union
                 select '34'                  union
                 select '254B'                  union
                 select '276'                  union
                 select '65'                  union
                 select '78'                  union
                 select '178'                  union
                 select 'TEXTVALUE        union
                 select '221A'                  union
                 select '209'                  union
                 select '96A'                  union
                 select '73'                  union
                 select '190'                  union
                 select '262'                  union
                 select '258'                  union
                 select '278'                  union
                 select '194A'                  union
                 select '46'                  union
                 select '227A') as charachters_to_insert

 

Now, I can start working with the numeric values that have A LETTER IN IT

 

 

select * from blah where isnumeric(mixed_charachters)<>1

Tuesday, August 31, 2010

Find your ReportServer Stored Procedures

Here is a source I found that will show you all the stored procedures that are stored in your SQL Server Reporting Services.

 

This is a staple for me!  It can get pretty crazy, not knowing what stored procedure goes to what report!

 

 

;
with xmlnamespaces (
default 'http://schemas.microsoft.com/sqlserver/reporting/2005/01/reportdefinition',
'http://schemas.microsoft.com/SQLServer/reporting/reportdesigner' as rd
)
select  name,x.value('CommandType[1]','VARCHAR(50)') as CommandType,x.value('CommandText[1]','VARCHAR(50)') as CommandText,
        x.value('DataSourceName[1]','VARCHAR(50)') as DataSource
from    (select name,cast(cast(content as varbinary(max)) as xml) as reportXML
         from   NRDEV1.ReportServer.dbo.Catalog
         where  content is not null
                and TYPE = 2) a
cross apply reportXML.nodes('/Report/DataSets/DataSet/Query') r (x)
where   x.value('CommandType[1]','VARCHAR(50)') = 'StoredProcedure'
order by name

Thursday, June 24, 2010

SSRS multi-select (easy way!)

 

Open Visual Studio Business Intellegence Studio

Open an existing project or create a new project.

 

Select the Data Tab image
create new DataSet image
   
   

 

call this dataset Select:

Here is my select statement.
select * from (
select 'basket ball' as ball
union select 'baseball'
union select 'foot ball'
union select 'nerf ball'
) t where t.ball in(@ball)








Call this ddl_select (this will be the drop-down menu you need for the multi-select)









 









select 'basket ball'
union select 'baseball'
union select 'foot ball'
union select 'nerf ball'








if you have a debug table you want to test your values (see how they are written, here’s some code:









 









if object_id('admin_ssrs_log') is null 
  begin
    CREATE TABLE [dbo].[admin_ssrs_log] ([ssrsID] [int] IDENTITY(1, 1)
                                                        NOT NULL,
                                         [PageName] [varchar](255) NULL,
                                         [Username] [nvarchar](520) NOT NULL,
                                         [runDate] [datetime] NOT NULL
                                                              CONSTRAINT [DF_ssrs_log_runDate] DEFAULT (getdate()),
                                         [string] [varchar](max) NULL
                                                                 CONSTRAINT [DF_ssrs_log_string] DEFAULT ('none'),
                                         [Stored Procedure] [nvarchar](255) NULL) 
  end
insert  dbo.admin_ssrs_log (PageName,
                            Username,
                            runDate,
                            string,
                            [Stored Procedure])
values  (
         'test multi-select parameters', -- PageName - varchar(255)
         'domain\username', -- Username - nvarchar(520)
         getdate(), -- runDate - datetime
         @ball, -- string - varchar(max)
         '(code behind execution; no stored proc)'  -- Stored Procedure - nvarchar(255)








 









Now, create the multi-select drop down for “ball”









image









 









here you can select the options (but you aren’t done yet! the clincher is next):









image









 









The multi-select parameter is written but SQL Server needs it parsed in a certain way.









(oh my, this is soooo easy!)









 









1.  Go to your data tabl image









2.  Edit the dataset that needs the @ball parameter.









image









 









3.  Select the Parameters tab









image

















































































 









The key is to use the Replace function and the Join function









 









Chagne your value









from =Parameters!ball.Value









to     =Replace(Join(Parameters!ball.Value,", ")," ", "")









 









voila.  your multi-select will work every time!









 









 









helpful source (kinda obscure, but here it is)

Monday, June 21, 2010

writing sequential numbers with a zero prefix

 

At times you may need a zero as a prefix to sequential numbers

ie:

00001
00002..

00009
00010…

Here is test code that flows through one to ten thousand:

 

declare @number int,
  @prefix varchar(20),
  @display_number varchar(20)
-----------------------------
set @number=0 
while @number<10000
  begin
    set @number=coalesce(@number, 0)
    -----------------------------
    if len(convert(varchar(20), @number))>0
      and @number<>0 
      begin
    -- ones place
        if len(convert(varchar(20), @number))=1
        begin 
          set @display_number='0000'+convert(varchar(20), @number)
        print @display_number
        end
    -- tens place
        if len(convert(varchar(20), @number))=2 
        begin
          set @display_number='000'+convert(varchar(20), @number)
        print @display_number
        end
    -- hundreds place
        if len(convert(varchar(20), @number))=3 
        begin
          set @display_number='00'+convert(varchar(20), @number)
        print @display_number
        end
    -- thousands place
        if len(convert(varchar(20), @number))=4 
        begin
          set @display_number='0'+convert(varchar(20), @number)
        print @display_number
        end
      end
    set @number=@number+1  
  end

Saturday, June 12, 2010

adding windows permissions to Navision

 

my file location: ..\Program Files\Microsoft Dynamics NAV\CSIDE Client

 

 

1.  copy the file xp_ndo.dll

save it to a fixed location on the server’s location.

image

note: if this is a local machine: I typically save it locally to a C:\Data folder so I know the info should NOT be deleted!

 

2.  Open SQL Server Managmenet Studio

3.  (be careful!) tier down to the master database



4.  Programmability –> Extended Stored Procedures
5.  Right-Click “New extended stored procedure
name it xp_ndo_enumusersids
DLL field select the full file path for the xp_ndo.dll
image 

image

my location is c:\Data

6.  Assign permissions to the public role: IN the extended Stored Procedures properties, click on “permissions” then “search” type in “public” then OK.  Then assign execute permissions to Public

7.  repeat the previous steps and make another extended stored procedure which is exactly identitcal except this one must be called xp_ndo_enumersgroups in stead of xp_ndo_enumusersids
 

 

special thanks go to Lars Lohndorf-Larsen – Microsoft Dynamics UK

 

But wait! There’s more!

 

You may just get this error as well.

 

image

 

You have to put a trace flag on your database.  This enables certain properties in SQL Server.

In SQL Server 2005, a user trying to use a program (..an application role) cannot access metadata (meaningful info you need) outside its own database because application roles are not associated with a server-level principal.

This is a change from earlier versions of SQL Server.
Setting this global flag allows for application roles to access server-level metadata

 

1.  Open SQL Server Manager

2.  Right Click SQL Server –> Properties –> Advanced tag.

3.  Scroll down until you see “Startup Parameters”.. type in –T4616.

4.  Click OK. 

5.  Restart SQL Server

(this site helped: http://plataan.typepad.com/microsoftdynamics/2007/11/how-to-set-trac.html)

Monday, June 7, 2010

ERROR: “Cannot insert the value NULL into column 'permission path', table '@temp'; column does not allow nulls. INSERT fails.”

 

I was scripting a senddb code

image

and got this error:

“Cannot insert the value NULL into column 'permission path', table '@temp'; column does not allow nulls. INSERT fails.”

 

Descriptive huh!?

This has to do with a profile name not being entered.

image

 

image

image

 

View what the name of the profile is.  mine is “testForMailJob”

image

 

and I updated my code to include the profile name:

image

Wednesday, June 2, 2010

decimal calculation Phakery

I have written a calculation inside a column called written amt.
I multiplied the Amount * Net Weight which is the Net Weight times Amount.
But when I verified the amounts by a unit test (SQL Mag’s InstantDoc ID #37428 or Wikkipedia)
certain values failed.
Notice the Net Weight column for the failed lines:

Object1: failed rows
image

All the failed rows had net weights of decimals
Cross reference with the amounts.

Then I knew the column specification for my table was smaller than the source table.
source table: decimal (38,20)
destination table (from the select): (38,2)
so, what I see are the truncated amounts shoved by the wayside to give me rounded numbers.
voila.
[insert large exclamation of “DUH” here]

Tuesday, May 11, 2010

Weighted Averages in SQL Server

Here is a screen shot of my brain dump regarding weighted averages.
image
The Financial Dictionary says:
Weighted Average definition
An average in which each quantity to be averaged is assigned a weight. These weightings determine the relative importance of each quantity on the average. Weightings are the equivalent of having that many like items with the same value involved in the average.
Investopedia Commentary
To demonstrate, let's take the value of letter tiles in the popular game Scrabble.
Value: 10 8 5 4 3 2 1 0
Occurrences: 2 2 1 10 8 7 68 2
To average these values, do a weighted average using the number of occurrences of each value as the weight. To calculate a weighted average:
1. Multiply each value by its weight. (Ans: 20, 16, 5, 40, 24, 14, 68, and 0) 2. Add up the products of value times weight to get the total value. (Ans: Sum=187) 3. Add the weight themselves to get the total weight. (Ans: Sum=100)
4. Divide the total value by the total weight. (Ans: 187/100 = 1.87 = average value of a Scrabble tile)
here's a start:
SELECT     ItemToCount, price AS value, COUNT(ItemToCount) AS weight, COUNT(ItemToCount) * price AS value_times_weight FROM         SalesTable GROUP BY ItemToCount, price ORDER BY ItemToCount
research used:
(I played “with rollup” to give me subtotals):
http://msdn.microsoft.com/en-us/library/ms189305(SQL.90).aspx
Webster’s Dictonary lookup on Weighted Average:
http://dictionary.reference.com/browse/weighted+average

Sunday, May 9, 2010

Happy Mother's Day to All!

My daughter made me cry... on Mother's Day!


Friday, May 7, 2010

Alert on Job Failure (email alert)

I have had such luck getting a single failure alert to happen.  Here’s what I did.
I presume you have an email account set up in SQL Server.

Right-click SQL Server Agent –> Properties
image
Select Alert System.
Turn on Enable mail Profile and click OK. 
Then repeat by turning it off! Then turn it back on.
image
Then, I created a job called fail that would force to fail.
Right-click the ill-fated job –> Properties
 image
select Notifications
don’t mess with Alerts (they annoy me at times; my ignorance shows).
image
Make the ill-fated-job  run so it can fail; check your mail.  If you have enabled mail properly, (turn off + turn on SQL Alert system) you typically won’t have any problems

image

Error: the encrypted value for the "logoncred" configuration setting cannot be decrypted

I got an error:

”the encrypted value for the "logoncred" configuration setting cannot be decrypted”
open cmd as Administrator
Navigate to: C:\Program Files\Microsoft SQL Server\90\Tools\Binn
RSKeyMgmt.exe should be in that directory.
type: rskeymgmt –d and it overrides the Reporting Services Management Console

Thursday, May 6, 2010

Merged Cells in Reporting Services

 
When a report with headers is exported to Excel, you will most likely get merged cells.

 mergedCells
This can mess up sorting inside your row data amongst other things.
[insert grumbling here]

How to enable SimplePageHeaders=True

A little Homework: Encryption Keys

Before you modify the xml file (.config file), you may stomp on the encryption data.

Encryption keys are based partly on the profile information of the Report Server service. If you change the user identity used to run the Report Server service, you must update the keys accordingly. If you are using the Reporting Services Configuration tool to change the identity, this step is handled for you automatically.

If initialization fails for some reason, the report server returns an RSReportServerNotActivated error in response to user and service requests. In this case, you may need to troubleshoot the system or server configuration. For more information, see Troubleshooting Initialization and Encryption Key Errors.

source: MSDN doc 157133

Ok… you ready to go ahead and modify the config file?

Modify RSReportServer.Config file on the server you need changing.  (do it locally to test first).

rsreportserver.config file location:
If you have a default installation , the location is C:\Program Files\Microsoft SQL Server\MSSQL.2\Reporting Services\ReportServer


Inside the file, look for Extension Name="EXCEL"

  1. back up your config file
  2. You will have to add a few tags inside the .config file.  Something like this:

config-file





Microsoft gives you a very nondescript article about Excel Device Information, but defines terms for you.


NO need to restart the file; it is an xml file.  source
source:

msdn article
msdn discussion site
one of my top discussion/content sites I love: simple-talk
Special thanks to Mike Schetterer MSFT

Navision 5 finsql.exe error

finsqlexe
This came about when SQL Server cut out and was restarted.
A gal left for lunch with Navision minimized, opened it back up and found this error.
After searching across the internet for this error, I found that there are other causes.. hopefully this helps someone someday..

Who gets to ride with Mom this time?!!

Ava, Chase and Pomp are on their best behavior...

Wednesday, May 5, 2010

Dog Agility Videos I've enjoyed

Watching Elise Paffrath's videos have been an enjoyment.  I found her through ExpertVillage

SQL Server 2008 (Developer's version!)

If you are getting your feet wet into SQL Server, this is the license to get.

I bought a developer version of SQL Server 2008.  I am certified in SQL Server 2005 and  am slowly gaining in the learning curve with 2008.
If you have the money, buy it.  The developer license is exactly like the Enterprise edition (gobs of money!). 

Tuesday, May 4, 2010

Remote servers


How can you talk to another server on your network or across the internet?

There a lot of ways to skin a cat, and there are many ways of getting your through to the database you need to talk to.

Have on hand:

  • A personal computer you can play with (SQL Server Express?)
  • A windows login that is godlike (that can map to another computer). Password, etc.
Permissions

Practice on a personal computer you can play with -- SQL Server Express installed.
Then try it on a server on a network. If you gradually get the mapping of permissions down, you will understand how it works.

Think of a linked server as a rope bridge. The same permissions must be duplicated to the other server.
Windows permissions is a bit more tricky than that of a SQL login. You will find lots of discussions and many people relenting to SQL login permissions (I own my issue on that account!).

Try a script

What you need to do to make this work:

'[domain\[username]' : replace the text in the below script '[domain\[username]' with your own type of windows login.
this windows user name must match permissions exactly on the target server

'mylinkedserver' - you probably don't have a server called 'mylinkedserver', so find the name of the server/instance of your database you want to link to)..

EXEC master.dbo.sp_addlinkedserver @server = N'mylinkedserver', @srvproduct=N'SQL Server'

EXEC master.dbo.sp_addlinkedsrvlogin @rmtsrvname=N'mylinkedserver',@useself=N'True',@locallogin=NULL,@rmtuser=NULL,@rmtpassword=NULL

EXEC master.dbo.sp_addlinkedsrvlogin @rmtsrvname=N'mylinkedserver',@useself=N'True',@locallogin=N'[domain]\[username]',@rmtuser=NULL,@rmtpassword=NULL



GO

EXEC master.dbo.sp_serveroption @server=N'mylinkedserver', @optname=N'collation compatible', @optvalue=N'false'

GO

EXEC master.dbo.sp_serveroption @server=N'mylinkedserver', @optname=N'data access', @optvalue=N'true'

GO

EXEC master.dbo.sp_serveroption @server=N'mylinkedserver', @optname=N'dist', @optvalue=N'false'

GO

EXEC master.dbo.sp_serveroption @server=N'mylinkedserver', @optname=N'pub', @optvalue=N'false'

GO

EXEC master.dbo.sp_serveroption @server=N'mylinkedserver', @optname=N'rpc', @optvalue=N'true'

GO

EXEC master.dbo.sp_serveroption @server=N'mylinkedserver', @optname=N'rpc out', @optvalue=N'true'

GO

EXEC master.dbo.sp_serveroption @server=N'mylinkedserver', @optname=N'sub', @optvalue=N'false'

GO

EXEC master.dbo.sp_serveroption @server=N'mylinkedserver', @optname=N'connect timeout', @optvalue=N'0'

GO

EXEC master.dbo.sp_serveroption @server=N'mylinkedserver', @optname=N'collation name', @optvalue=null

GO

EXEC master.dbo.sp_serveroption @server=N'mylinkedserver', @optname=N'lazy schema validation', @optvalue=N'false'

GO

EXEC master.dbo.sp_serveroption @server=N'mylinkedserver', @optname=N'query timeout', @optvalue=N'0'

GO

EXEC master.dbo.sp_serveroption @server=N'mylinkedserver', @optname=N'use remote collation', @optvalue=N'true'

 

Troubleshooting: test the connection:



If you fall into any kinds of errors (I made a fake server to emulate an error):



Then, click the advanced technical error



Select the Message areas to get an error number and google the error number or the phrase; you will find some good some bad advice; stick to Microsoft or reputable websites.




 

If you have no errors, then you will call a table from the other server:
Select * from mylinkedserver.ReportServer.dbo.Catalog


 

Related articles (linked servers between 2005 and 2008)

Calling a linked server (microsoft's site)

Use this helpful documentation when scripting out linked servers!