Search this insane blog:

Showing posts with label T-SQL. Show all posts
Showing posts with label T-SQL. Show all posts

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 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

Monday, May 3, 2010

Database Stuck in Restoring State?


Is your database stuck in (Restoring…) state?





Easy!Here, I have a database called debug, stuck in the restoring state.I run this script:
RESTORE
DATABASE [debug]
WITH
RECOVERY

Results should return something like this:



RESTORE DATABASE successfully processed 0 pages in 5.414 seconds (0.000 MB/sec).

Tuesday, April 20, 2010

loop through records

-- runningCaseTotal


DECLARE @rowcount INT,
@item_no VARCHAR(20),
@id INT -- identity key to track rows with
SET @rowcount = (SELECT COUNT(*) FROM dbo.production_availability_ready_not_ready)
-----------------------------
--UPDATE dbo.production_availability_ready_not_ready
--SET runningCaseTotal = NULL
-----------------------------

WHILE @rowcount>0
BEGIN
-------TESTING-----------------
--PRINT 'ROWCOUNT: ' + CONVERT(VARCHAR(20),@rowcount)
--SET @id = (SELECT TOP 1 id FROM dbo.production_availability_ready_not_ready WHERE runningCaseTotal IS null)
--PRINT '..processing @id ' + CONVERT(VARCHAR(20),@id)
--SET @item_no = (SELECT [Item No_] FROM dbo.production_availability_ready_not_ready WHERE id = @id)
--UPDATE dbo.production_availability_ready_not_ready SET runningCaseTotal = 0 WHERE id = @id
--PRINT 'item_no: ' + CONVERT(VARCHAR(20),@item_no)
--PRINT '---------'
-----------------------------




SET @rowcount = @rowcount-1;


END

Thursday, March 18, 2010

HTML codes


Below is a good resource if you need to re-build information from a databaase and parse it into an http:// website address
(hint-hint.. namely Reporting Services links too!)



DECLARE @EXCLAMATION VARCHAR(20),@STAR VARCHAR(20),@SINGLE_QUOTATION VARCHAR(20),@OPEN_PARENTHESIS VARCHAR(20),@CLOSE_PARENTHESIS VARCHAR(20),@SEMI_COLON VARCHAR(20),@COLON VARCHAR(20),@AT_SIGN VARCHAR(20),@AMPERSIGN VARCHAR(20),@EQUALS VARCHAR(20),@PLUS VARCHAR(20),@DOLLAR VARCHAR(20),@FORWARD_SLASH VARCHAR(20),@QUESTION_MARK VARCHAR(20),@PERCENT VARCHAR(20),@NUMBER_SIGN VARCHAR(20),@OPEN_BRACKET VARCHAR(20),@CLOSE_BRACKET VARCHAR(20)


SELECT @EXCLAMATION =
'0.21%',--!@STAR ='%2A',--*@SINGLE_QUOTATION ='0.27%',--'@OPEN_PARENTHESIS ='0.28%',--(@CLOSE_PARENTHESIS ='0.29%',--)@SEMI_COLON ='%3B',--;@COLON ='%3A',--:@AT_SIGN ='0.4%',--@@AMPERSIGN ='0.26%',--&@EQUALS ='%3D',--=@PLUS ='%2B',--+@DOLLAR ='0.24%',--$@COMMA ='%2C',--,@FORWARD_SLASH ='%2F',--/@QUESTION_MARK ='%3F',--?@PERCENT ='0.25%',--%@NUMBER_SIGN ='0.23%',--#@OPEN_BRACKET ='%5B',--[@CLOSE_BRACKET ='%5D'--]



declare @space varchar(20),@exclamationpoint varchar(20),@doublequotes varchar(20),@numbersign varchar(20),@dollarsign varchar(20),@percentsign varchar(20),@ampersand varchar(20),@singlequote varchar(20),@openingparenthesis varchar(20),@closingparenthesis varchar(20),@asterisk varchar(20),@plussign varchar(20),@comma varchar(20),@minussignhyphen varchar(20),@period varchar(20),@slash varchar(20)
-----------------------------
set @space =' 'set @exclamationpoint='!'set @doublequotes ='"'set @numbersign ='#'set @dollarsign='set @percentsign ='%'set @ampersand ='&'set @singlequote=''''set @openingparenthesis ='('set @closingparenthesis =')'set @asterisk ='*'set @plussign ='+'set @comma =','set @minussignhyphen ='-'set @period ='.'
set @slash ='/'



set @percentsign ='%'
set @ampersand ='&'
set @singlequote=''''
set @openingparenthesis ='('
set @closingparenthesis =')'
set @asterisk ='*'
set @plussign ='+'
set @comma =','
set @minussignhyphen ='-'
set @period ='.'
set @slash ='/'

Saturday, December 19, 2009

What is the difference between SET and SELECT variables

If you have a set, you know for sure it will return only one value.

if you use SELECT to set a variable:
select @myVariable = myTable.MyCol


or..

if you use the SET statement to set a variable

set @myVariable = myTable.MyCol


At certain times, with the SELECT statement, you can return more than one row.

That so much a problem?
Well, I think it potentially could be.
There can be no error that is returned when you get multiple rows.

here is a good source:
http://www.mssqltips.com/tip.asp?tip=1888

Thursday, July 16, 2009

list local files from SQL Server 2005 (xp_cmdshell enabled)

-- found this on the sqlserver central website.

USE master
GO
CREATE PROCEDURE dbo.sp_ListFiles
@PCWrite varchar(2000),
@DBTable varchar(100)= NULL,
@PCIntra varchar(100)= NULL,
@PCExtra varchar(100)= NULL,
@DBUltra bit = 0
AS
SET NOCOUNT ON
DECLARE @Return int
DECLARE @Retain int
DECLARE @Status int
SET @Status = 0
DECLARE @Task varchar(2000)
DECLARE @Work varchar(2000)
DECLARE @Wish varchar(2000)

SET @Work = 'DIR ' + '"' + @PCWrite + '"'

CREATE TABLE #DBAZ (Name varchar(400), Work int IDENTITY(1,1))

INSERT #DBAZ EXECUTE @Return = master.dbo.xp_cmdshell @Work

SET @Retain = @@ERROR

IF @Status = 0 SET @Status = @Retain

IF @Status = 0 SET @Status = @Return

IF (SELECT COUNT(*) FROM #DBAZ) < 4
BEGIN
SELECT @Wish = Name FROM #DBAZ WHERE Work = 1
IF @Wish IS NULL
BEGIN
RAISERROR ('General error [%d]',16,1,@Status)
END
ELSE
BEGIN
RAISERROR (@Wish,16,1)
END
END
ELSE
BEGIN
DELETE #DBAZ WHERE ISDATE(SUBSTRING(Name,1,10)) = 0 OR SUBSTRING
(Name,40,1) = '.' OR Name LIKE '%.lnk'
IF @DBTable IS NULL
BEGIN
SELECT SUBSTRING(Name,40,100) AS Files
FROM #DBAZ
WHERE 0 = 0
AND (@DBUltra = 0 OR Name LIKE '% %')
AND (@DBUltra != 0 OR Name NOT LIKE '% %')
AND (@PCIntra IS NULL OR SUBSTRING(Name,40,100) LIKE @PCIntra)
AND (@PCExtra IS NULL OR SUBSTRING(Name,40,100) NOT LIKE @PCExtra)
ORDER BY 1
END
ELSE
BEGIN
SET @Task = ' INSERT ' + REPLACE(@DBTable,CHAR(32),CHAR(95))

+ ' SELECT SUBSTRING(Name,40,100) AS Files'

+ ' FROM #DBAZ'

+ ' WHERE 0 = 0'

+ CASE WHEN @DBUltra = 0 THEN '' ELSE ' AND Name LIKE ' + CHAR(39) + '% %' + CHAR(39) END

+ CASE WHEN @DBUltra != 0 THEN '' ELSE ' AND Name NOT LIKE ' + CHAR(39) + '% %' + CHAR(39) END

+ CASE WHEN @PCIntra IS NULL THEN '' ELSE ' AND SUBSTRING (Name,40,100) LIKE ' + CHAR(39) + @PCIntra + CHAR(39) END

+ CASE WHEN @PCExtra IS NULL THEN '' ELSE ' AND SUBSTRING

(Name,40,100) NOT LIKE ' + CHAR(39) + @PCExtra + CHAR(39) END

+ ' ORDER BY 1'
IF @Status = 0 EXECUTE (@Task) SET @Return = @@ERROR
IF @Status = 0 SET @Status = @Return
END
END
DROP TABLE #DBAZ
SET NOCOUNT OFF
RETURN (@Status)
GO


--And to test:
--EXECUTE sp_ListFiles 'c:\ftp',NULL,NULL,NULL,1

Friday, July 10, 2009

bcp format file: sundry thoughts

I am indexing this link for my own edification. 

http://msdn.microsoft.com/en-us/library/ms191516.aspx

Sunday, July 5, 2009

What are the columns in that table?

Oh my.
I wish I found this many years earlier.

use MyDatabase
go

SELECT column_name, data_type
FROM
INFORMATION_SCHEMA.COLUMNS
WHERE
TABLE_NAME = 'MyTable'
ORDER
BY ORDINAL_POSITION




replace MyDatabase and MyTable with your database and table values

Friday, June 26, 2009

RESTORE HEADERONLY

If you don't know which backup files hold the right database to restore?
If you need to locate the correct backup file to restore, use RESTORE BACKUP WITH HEADERONLY option.


See msdn definition file:
http://msdn.microsoft.com/en-us/library/aa238455(SQL.80).aspx

Wednesday, June 24, 2009

How Heavy is my SQL Server database is being used?

I wrote this script after studying about I/O statistics.
This view is based on sys.dm_io_virtual file status
This looks at the physical file reads and writes, and how many times it stalled.
If it is stalling, you can dig deeper to see what is causing the stall… then you can partition the offensive table/object etc.

Cool system view!


-----------@Mydatabase-----------------------

-- type in name of database between the ''
-- or type in 'all' between the ''
--------------------------------------------

declare @Mydatabase nvarchar(255)
set @Mydatabase = 'all'
--------------------------------------------

if @Mydatabase = 'all'
begin

select

db_name(database_id)
as database_name,
file_name(file_id)
as file_name,
sample_ms,
num_of_reads,
num_of_bytes_read,
io_stall_read_ms,
num_of_writes,
num_of_bytes_written,
io_stall_write_ms,
io_stall,
size_on_disk_bytes

from
sys.dm_io_virtual_file_stats(null, null) ;
end
else
begin
declare @database int
set @database = db_id(@Mydatabase) ;

select

db_name(database_id)
as database_name,
file_name(file_id) as file_name,
sample_ms,
num_of_reads,
num_of_bytes_read,
io_stall_read_ms,
num_of_writes,
num_of_bytes_written,
io_stall_write_ms,
io_stall,
size_on_disk_bytes
from

sys.dm_io_virtual_file_stats(@database, null) ;
end