Showing posts with label stored. Show all posts
Showing posts with label stored. Show all posts

Thursday, March 29, 2012

adding a stored proc to a publication

Hi

I created a publication (merge anonymous via Web) - the subscriber already had the data, so there was no need to to initialize data and schema.

The problem is when it comes to adding a new stored proc to the publication. I create the proc, add it as an article to the publication and recreate the snapshot ok, but then the synchronisation fails. I presume this is because the stored proc does not exist at the subscriber. I bet it would work if I had initialized the schema and data, but due to the size of the data this is not practical.

If I manually create the proc at the subscriber then it works fine - but this defeats the purpose somewhat.....

Any ideas ?

thanks
BruceSince the subscription was created as no-sync, you will need to manually create the proc on the subscriber. You could create different publications for tables and stored procs and workaround that way. Now you can initialize the subscriber for the publication with the stored proc (and other smaller articles if you wish) and large data publication can stay intact (as no-sync)|||Thanks for the suggestion - a good workaround for now....

Sunday, March 25, 2012

Adding a date to a report

I'd like to add a date in the heading of the report. Since the current date is not part of the stored procedure that I'm using how can I get the date? I was hoping for a built-in function of some kind.

you should be able to just add a textbox and enter the expression

= System.DateTime.Now()

|||

Are you referring to referencing a date/time other than the current date/time? If so, I would like to know how to do this as well. I have a DTS (SSIS) job that i want to reference the time it ran in my report. I could do the same thing with a stored proc if I had to.

Thanks everyone.

|||No, all I needed was the date/time the report is produced and I already received that answer.sql

Tuesday, March 20, 2012

Addicted to Stored Procedures: A time series problem. Is it possible?

It's been about two weeks since I first began using SQL Stored procedures and now I am thinking already about changing many of my plans and doing those operations in them. There is a problem I want to address and see if it is possible to accomplish it in SQL Server instead of the client C# code.
I have a time series. In simplified presentation it is a table of two columns. The first one is float, the second is DateTime. There might be quite a few rows in the table:

A1 ... DT1
A2 ... DT2
................
An.... DTn
What I need to do is to find patters among A1,A2,....An elements. They vary in magnitude in a rather random order. They constitute what some would call a Markov chain. I demonstrate what I want in a couple of real life examples that I would not have a problem to run in my C# code at all.

(1) element Ak may be only 90% of the element in the previous row Ak-1. I want to catch it. I want to get the DateTime stamp when it happened. The next step is: I want to go down the chain of rows and find the element Am which rebounds to the magnitude of the element Ak. In other words Am==Ak. I want to remember its DateTime stamp.Then I want to find all elements in the chain of rows that follow the same pattern.

How can I do it in SQL language? Is it possible? I've been thinking about creating a bunch of temporary tables with rows shifted up by one and and destroying them after a pattern has been found in the same rows of many tables.

(2) I want to collect a distribution of many such patterns and analyze then in C# code but the elementary block is the operation I described in point (1). If I could get a cue as to how to go about it I could figure out the rest, I hope.

I learn by examples, by looking at code samples. So far I haven't seen anything that fits this task. If anyone could send me in such direction it would be great. Most of the things I've seen is "SELECT FROM CUSTOMERS," etc.

A somewhat related question. Years ago I stumbled in MSN help on a set of Math routines (they could have been part of a class) that were designed specifically for analyzing patters. It is not the Math class, I have looked into it. It is something different. I cannot find them now. I did not save a bookmark back then.

Does anyone know what I am talking about: math functions for time series analysis?

Thanks.

Time Series Analysis is actually a part of Data Mining for SQL Server, I just found out, but since I have an SQLEXPRESS I probably cannot use it. Right? I have to get the full server for that?|||

OK, I've been trying to write a stored procedure with some SQL statements that conceivably could handle the task at hand.

This is what I've come up with. It is assumed that there is a table tick_M, it contains two columns: bid and dateTimed, I create a temporary table tempTable1 with three columns. In addition to bid and dateTimed there will be a RowNumber column. Thus we end up with 3 columns. Then I want to create yet another table from temporary tempTable1 which will consist of all the rows of the first table starting from row # 2. Then I want to make a LEFT INNER JOIN ON rownumber1 = rownumber2.

This is the code.

WITH tempTable1 AS
( SELECT ROW_NUMBER() OVER (ORDER BY dateTimed) AS 'RowNumber1',
bid OVER AS 'bid1',
dateTimed OVER AS 'dateTimed1'
FROM tick_M )
GO
WITH tempTable2 AS
( SELECT ROW_NUMBER() OVER (ORDER BY dateTimed1) AS 'RowNumber2',
bid1 OVER AS bid2,
dateTimed1 OVER AS dateTimed2
FROM tempTable1 WHERE RowNumber1 > 1)
GO
SELECT tempTable1.bid1, tempTable1.dateTimed1, tempTable1.RowNumber1,
tempTable2.bid2, tempTable2.dateTimed2
FROM tempTable1 AS Result
LEFT OUTER JOIN tempTable2 ON tempTable1.RowNumber1 =
tempTable2.RowNumber2
GO

The trouble is I get compilation errors. Could anyone help me here?

Thanks.

|||

Alex,

I neither understood nor thoroughly checked your code however at first glance I see some syntax errors. Remove "go" spread in your SQL. CTEs do not have a go after them. ie:

with tempTable1 as ( ... ),
tempTable2 as ( ... ) ...

|||

CetinBasoz wrote:

Alex,

I neither understood nor thoroughly checked your code however at first glance I see some syntax errors. Remove "go" spread in your SQL. CTEs do not have a go after them. ie:

with tempTable1 as ( ... ),
tempTable2 as ( ... ) ...

Cetin hi,

It gives me an error even before a GO. It says "Incorrect syntax near OVER" pointing to the first OVER. I removed the GOs.

Thanks for your help.

|||

Yes I'd error too:) Why do you have multiple over there (you might - but then you should also have an partiotion and/or order by clause to use with over).

Anyway Alex,

I think you should rephrase your original question with sampling (and prefarably with ready to generate code for sample data). I didn't understand it and probably no one did.

Just cleared code a bit w/o checking extensively.
WITH tempTable1 AS

( SELECT ROW_NUMBER() OVER (ORDER BY dateTimed) AS 'RowNumber1',

bid AS 'bid1',

dateTimed AS 'dateTimed1'

FROM tick_M )

WITH tempTable2 AS

( SELECT ROW_NUMBER() OVER (ORDER BY dateTimed1) AS 'RowNumber2',

bid1 AS bid2,

dateTimed1 AS dateTimed2

FROM tempTable1 WHERE RowNumber1 > 1)

SELECT tempTable1.bid1, tempTable1.dateTimed1, tempTable1.RowNumber1,

tempTable2.bid2, tempTable2.dateTimed2

FROM tempTable1 AS Result

LEFT OUTER JOIN tempTable2 ON tempTable1.RowNumber1 =

tempTable2.RowNumber2

|||

CetinBasoz wrote:

Yes I'd error too:) Why do you have multiple over there (you might - but then you should also have an partiotion and/or order by clause to use with over).

Anyway Alex,

I think you should rephrase your original question with sampling (and prefarably with ready to generate code for sample data). I didn't understand it and probably no one did.

Cetin hi,

Thank you for the code. Unfortnately it did not comply. I reworked the code entirely and came up with something that did:

USE hist_Tick
GO
DROP TABLE #tempTable_1
GO
SELECT ROW_NUMBER() OVER (ORDER BY dateTimed) AS 'RowNumber1',
bid AS 'bid1',
dateTimed AS 'dateTimed1'
INTO #tempTable_1
FROM dbo.tick_MSFT
GO
DROP TABLE #tempTable_2
SELECT ROW_NUMBER() OVER (ORDER BY dateTimed1) AS 'RowNumber2',
bid1 AS 'bid2',
dateTimed1 AS 'dateTimed2'
INTO #tempTable_2
FROM #tempTable_1
WHERE RowNumber1 > 1
GO
DROP TABLE #tempTable_3
GO
SELECT DISTINCT bid1, dateTimed1, RowNumber1, bid2, dateTimed2
INTO #tempTable_3
FROM #tempTable_1, #tempTable_2
WHERE RowNumber1 = RowNumber2
ORDER BY dateTimed1
GO
SELECT * FROM #tempTable_3
GO

The idea was to create a JOIN table with values from two original tables in such a way that the second table has all rows (values) shifted by one row forward (down). The combination table naturally should be one row shorter than the original tables. I got displayed #tempTable_3. It looks perfect.

Thanks.

|||

I see what you mean now:) It could be done even with VFP SQL using a single query joining the table with itself :) Would this do?

select
t1.bid as bid1, t1.datetimed as datetimed1, t2.bid as bid2, t2.datetimed as datetimed2
from timedSeries t1 left join timedSeries t2 on t1.DateTimed < t2.dateTimed
where t2.DateTimed = (select min(datetimed) from timedSeries where dateTimed > t1.dateTimed) or t2.dateTimed is null

Or this one with CTE:

with tSeries as ( select row_number() over (order by dateTimed) as rowNum, bid, datetimed from timedSeries )
select
t1.bid as bid1, t1.datetimed as datetimed1, t2.bid as bid2, t2.datetimed as datetimed2
from tSeries t1 left join tSeries t2 on t1.rowNum = t2.rowNum - 1

|||

Cetin hi,

Thank you very much. I switched to SQLEXPRESS because I could not handle a simple problem in C# dealing with VFP: I could not figure out how to write into the tables. I could read OK, could write into VFP tables, update them using XML but could not write directly. The mapping of columns killed me. Now I do not regret that I switched to SQL Server. I think, overall, it will be a more appropriate server for me.

But I will look into your code. I am also discovering additional commands in Transact-SQL which possibly will be even more helpful for me in this task.

Incidentally, I ran into a problem dropping the temporary tables in that query that I showed. When the query runs the first time DROP TABLE commmand causes an error. Conditional statement IF OBJECT_ID ('#tempTable_1') IS NOT NULL before it did not do anything. It appears SQL server ignores it during execution.

Thanks.

|||

Writing to VFP tables are straight forward but I didn't mean why you chose SQLEXPRESS:) I too like MSSQL and trying to learn it in depth. I meant that SQL would even work within VFP and supported since years (remember VFP supports much less SQL syntax than MSSQL does).

I don't think you need to drop a temp table there and also I don't think you need a temp table.

|||

Well, in this case, I am done with that stored procedure (DROPs aren't needed is a good news). I am actually having second thoughts on that. I think I can do FETCH row in a loop with cursors. I did not realize it until today. Now I know. It is all I need. I will rectify my knowledge in that area, write a few queries and, hopefully, it will take off. I am especially pleased that a bulk of calculations could be done at the database.

Now, with VFP I still do not understand how I can use it in here since now all my calculations, data retreival from a network server is done in C#. I use MSSQL for data storage and hopefully for most of analysis of historical data. Some analysis will be done in C# but that will be real time data analysis. I need to interact with the SQL server almost all the time but I could not easy interact with VFP database--it was all onesided. Although I do have another project still unfinished. I may use VFP database for the other one all the way. That project is also in C# but over there the data flow is slow and interactive and the volume is small.

Thanks.

|||

If data flow is slow then you don't need VFP:)

We are having a communication problem here. I didn't mean "do it in VFP". I meant those 2 SQL code would work better than your temptable approach. Try them and choose one.

added two more user parameters

I have a stored procedure that works fine in reporting services. It grabs the total of Yes's and No's by dates . But then i went ahead and added 2 more parameters to the proc, and now the totals are all wrong. I dont understand how that can mess everything up. Here is the previous stored proc, that gives the correct sum.

Code Snippet

ALTER PROCEDURE [dbo].[Testing_Questions_ALL_YESOrNO]

@.Question char(80)

AS

BEGIN

SELECT

Qry_Questions.Question

, Qry_Questions.Date

, Qry_Questions.response

, B.Total

FROM Qry_Questions

INNER JOIN Qry_Sales_Group

ON dbo.Qry_Questions.sales_person_code COLLATE SQL_Latin1_General_CP1_CI_AS = dbo.Qry_Sales_Group.SalesPerson_Purchaser_Code

INNER JOIN

( Select COUNT(qq.response)as Total, Question, Date, response

FROM Qry_Questions qq

Where qq.response in ('Yes','No')

GROUP by qq.[Question] , qq.Date,qq.response ) B

ON Qry_Questions.Date = B.Date AND

Qry_Questions.Question =B.Question and

Qry_Questions.response=B.response

WHERE Qry_Questions.[Response Type]='YesNo' and Qry_Questions.Question=@.Question

GROUP BY Qry_Questions.question,Qry_Questions.Date,Qry_questions.Response,B.Total

ORDER BY Qry_Questions.Question, Qry_Questions.Date

END

SET NOCOUNT OFF

Here is the edited version which only has two new parameters added to the proc. The edits are highlighted.

Code Snippet

ALTER PROCEDURE [dbo].[Testing_Questions_ALL_YESOrNO_Totals]

(@.Region_Key int=null,@.QuestionCode char(5),@.Question char(80))

AS

BEGIN

SELECT

Qry_Questions.Question

, Qry_Questions.Date

, Qry_Questions.response

, B.Total

FROM Qry_Questions

INNER JOIN Qry_Sales_Group

ON dbo.Qry_Questions.sales_person_code COLLATE SQL_Latin1_General_CP1_CI_AS = dbo.Qry_Sales_Group.SalesPerson_Purchaser_Code

INNER JOIN

( Select COUNT(qq.response)as Total, Question, Date, response

FROM Qry_Questions qq

Where qq.response in ('Yes','No')

GROUP by qq.[Question] , qq.Date,qq.response ) B

ON Qry_Questions.Date = B.Date AND

Qry_Questions.Question =B.Question and

Qry_Questions.response=B.response

WHERE Qry_Questions.[Response Type]='YesNo'

AND REGION_KEY=@.Region_Key

AND LEFT(Qry_Questions.[Question Code],2)IN (@.QuestionCode)

AND Qry_Questions.Question=@.Question

GROUP BY Qry_Questions.question,Qry_Questions.Date,Qry_questions.Response,B.Total

ORDER BY Qry_Questions.Question, Qry_Questions.Date

END

SET NOCOUNT OFF

Looks to me like when you're calling the SPROC, you're not passing in all of the Region_Key's or all of the possible Question_Code's. The SPROC syntax looks fine, assuming you're sure that the LEFT function is working correctly.

To find out exactly what's wrong, I would recommend isolating your changes one by one. Test the SPROC with only the Region_Key param and see what you get. If it's right, test with only the Question_Code param. Then try together. Problems like this are frequently caused by you not realizing that there are NULLs or blanks in your data, and so when you pass certain parameters, it will exclude other rows and therefore throw off your totals.

Hope that helps.
|||Just to add to above post, you have defined QuestionCode as char(5) in the param list, yet inside the proc you are doing left(question code, 2). You may be truncating some data and comparing with incorrect data.

|||

It's actually giving me a number way too big. A Sum way more then when i take the paramaters out. The Stored procedure works fine for another report i have with the same detail. But when i added these two additional parameters, for some reason it gives me a number way higher then if it didnt have any parameters at all.

|||Could you post the DDL and input params for the updated SP. I am hoping RegionKey is coming out of Qry_sales_Group and is it part of key or does it have multiple rows for the same value?
|||

I got it to work. I figured out that the sub query needed to be changed for this report because i was totaling based on region and question this time.

Code Snippet

INNER JOIN

( Select COUNT(qq.response)as Total, Question, Date, response

FROM Qry_Questions qq

INNER JOIN Qry_Sales_Group

ON Qry_Sales_Group.SalesPerson_Purchaser_Code = qq.sales_person_code COLLATE SQL_Latin1_General_CP1_CI_AS

Where qq.response in ('Yes','No')and Region_Key=@.Region_Key

GROUP by qq.[Question] , qq.Date,qq.response ) B

Thanks for the help. I went and piece every little piece til i relized it wasnt seperating them by regions.

Monday, March 19, 2012

Add User/Set Roles in Code and Read Roles

Can you write a stored procedure to add a user to your DB and set the roles the user belongs to?

I want to write a stored proc. to add users and set roles so it can be used in code instead of doing it manually.

After the user has been added and their roles set, can you write another stored proc. to give you what roles they belong to?Look for following sprocs in BOL and sp_helptext sprocs in QA

Might be a big help

sp_helprole
sp_helprotect
sp_helprolemember

sp_addrole
sp_addrolemember

However something you might need to check out

The Holy Book says:
sp_addrole cannot be used inside a user-defined transaction.|||insert into sysusers values
('new_user_id', 0, 'new_role_name', NULL, 0x00, getdate(), getdate(), 'dbo', NULL)|||Originally posted by Enigma
Look for following sprocs in BOL and sp_helptext sprocs in QA

Might be a big help

sp_helprole
sp_helprotect
sp_helprolemember

sp_addrole
sp_addrolemember

However something you might need to check out

The Holy Book says:
sp_addrole cannot be used inside a user-defined transaction.
sp_grantlogin, sp_grantdbaccess, sp_addrolemember, and sp_helpuser worked great. thanks.

Add user assembly in managed stored procedure

I am developing a managed stored procedure in VS.NET 2005 and I am trying to add a reference to an user developed assembly (not a system one) but adding a reference to it is not possible as it doesnt let me import assemblies but rather reference the few limited ones in a list. Why is this??

There are limitations to what you can do with CLR assemblies, that is the reason for the new SQL Server project template in VS 2005. Try the link below for more detailed info from Microsoft. Hope this helps.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnsql90/html/sqlclrguidance.asp

|||I found out how to do it, it can be done. Just add the user developed assembly to the SQL database assemblies and that will make it callable from a managed database object. The downsize as I see it is that you need to keep a repository of assemblies outside of the GAC...

Add Temp Parameters to a function

I am writing a set of functions and then a stored procedure to allow me to view some data in Reporting Services. I have written the first part of the function as shown ;

set ANSI_NULLS ON

set QUOTED_IDENTIFIER ON

GO

ALTER FUNCTION [dbo].[fnWTRTerrierData]

(@.vch_site_ref nvarchar (3), @.dt_src_date datetime)

RETURNS @.WeeklyTerrierRSPI TABLE

(Areacode varchar(2),siteref nvarchar(3),

estatename nvarchar(100), Securitised nvarchar(255),

unitref nvarchar(15), unittype nvarchar(30),

unittype_count int, tenantname nvarchar(100),

tenantstatus nvarchar(25), tenantstatus_count int,

unitstatus nvarchar(15), unitstatus_count int,

floortotal float, floortotocc float,

initialvacarea float, initialvacnet float,

TotalRent float, NetRent float,

FinalRtLsincSC float, DiscEndDate datetime,

ErvTot float, Leaseterm int,

leasestart datetime, rentreview nvarchar(255),

leaseend datetime, breakclause datetime,

tenancyterm datetime, landact nvarchar(255),

datadate datetime)

AS

BEGIN

INSERT @.WeeklyTerrierRSPI

SELECT Areacode, siteref, estatename, Securitised, unitref, unittype, unittype_count, tenantname,

tenantstatus, tenantstatus_count, unitstatus, unitstatus_count, floortotal, floortotocc,

initialvacarea, initialvacnet, TotalRent, NetRent, FinalRtLsincSC, DiscEndDate, ErvTot,

Leaseterm, leasestart, rentreview, leaseend, breakclause, tenancyterm, landact, datadate

FROM dbo.src_terrier

WHERE (datadate = @.dt_src_date) AND (siteref = @.vch_site_ref)

RETURN

END

I have then written a stored procedure which picks up the result set from the function and ultimately will deliver it to Reporting Services. The problem I have is that as soon as I run the CREATE PROCEDURE script, I get an error saying ;

Msg 216, Level 16, State 1, Procedure spWTRWeeklyTerrierData, Line 16

Parameters were not supplied for the function 'fnWTRTerrierData'.

How can I add parameters to the function sufficently so that I can run the Create procedure element of my code?

Regards

Post your Stored Procedure codes.|||

SET ANSI_NULLS ON

GO

SET QUOTED_IDENTIFIER ON

GO

CREATE PROCEDURE [dbo].[spWTRWeeklyTerrierData]

(@.vch_site_ref nvarchar(3), @.dt_src_date datetime)

AS

BEGIN

SET NOCOUNT ON;

SELECT fnWTRTerrierData.Areacode, fnWTRTerrierData.siteref, fnWTRTerrierData.estatename, fnWTRTerrierData.Securitised, fnWTRTerrierData.unitref, fnWTRTerrierData.unittype, fnWTRTerrierData.unittype_count, fnWTRTerrierData.tenantname,fnWTRTerrierData.tenantstatus, fnWTRTerrierData.tenantstatus_count, fnWTRTerrierData.unitstatus, fnWTRTerrierData.unitstatus_count, fnWTRTerrierData.floortotal, fnWTRTerrierData.floortotocc, fnWTRTerrierData.initialvacarea, fnWTRTerrierData.initialvacnet, fnWTRTerrierData.TotalRent, fnWTRTerrierData.NetRent, fnWTRTerrierData.FinalRtLsincSC, fnWTRTerrierData.ErvTot, fnWTRTerrierData.tenancyterm, fnWTRTerrierData.landact, fnWTRTerrierData.datadate

FROM fnWTRTerrierData

RETURN

END

|||

Looking at a stored procedure I pulled over from a SQL 2000 DB, I took out the elements that seems to resemble the function side

BEGIN

SET NOCOUNT ON;

RETURN

END

But I am still met with the same parameters message when I try to execute the SQL code to create the SP.

Regards

|||

ALTER FUNCTION [dbo].[fnWTRTerrierData]

(

@.vch_site_ref nvarchar (3),

@.dt_src_date datetime

)


Your table function is expecting 2 input parameter which you did not supply.
You will need to supply these 2 value to the function
for example

SELECT ...
FROM fnWTRTerrierData ('?', '2006-01-01')

Sunday, March 11, 2012

Add table and column descriptions/comments using script

Is it possible to add descriptions/comments to tables and columns using a
system stored procedure?Yes. See sp_addextendedproperty in the Books Online
--
Hope this helps.
Dan Guzman
SQL Server MVP
"Billy" <Billy@.discussions.microsoft.com> wrote in message
news:605D7315-2B68-409D-9560-997417CAC941@.microsoft.com...
> Is it possible to add descriptions/comments to tables and columns using a
> system stored procedure?|||Just what I was looking for!
Thanks a lot Dan.
Rgds
Per Christian Paasche
Norway
"Dan Guzman" wrote:
> Yes. See sp_addextendedproperty in the Books Online
> --
> Hope this helps.
> Dan Guzman
> SQL Server MVP
> "Billy" <Billy@.discussions.microsoft.com> wrote in message
> news:605D7315-2B68-409D-9560-997417CAC941@.microsoft.com...
> > Is it possible to add descriptions/comments to tables and columns using a
> > system stored procedure?
>
>

Thursday, March 8, 2012

Add relation to new table

If i add a new table to my database with a stored procedure, using that same sp or another can i also add a 1-M relationship with another table that is currently in the database. Please if you can provide an example.

Thank you,You need to add a foreign key constraint to the child table. Here's an example from SQL Server Books Online, which creates a job_id field that is a FK to the jobs table:

job_id smallint NOT NULL
DEFAULT 1
REFERENCES jobs(job_id)

That enough information? You can also modify an existing table.

Don

Add Permission Stored Procedure!

Hi all,
Just wondering, is their a system stored procedure i can use to grant
permission to all objects in a specified db to a specified user ?
Cheers,
AdamAdam,
What is your goal - read access or modification capability? Might look at
the db_datareader and db_datawriter fixed databse roles.
HTH
Jerry
"Adam Knight" <adam@.pertrain.com.au> wrote in message
news:%23Xs4Z5d1FHA.1032@.TK2MSFTNGP12.phx.gbl...
> Hi all,
> Just wondering, is their a system stored procedure i can use to grant
> permission to all objects in a specified db to a specified user ?
> Cheers,
> Adam
>|||Few hours ago:
http://groups.google.de/group/micro...9344927e9915da5
HTH, Jens Suessmeyer.

Add new SP without reinitializing

I have stored procedures that I want to add to the publication and
have them passed down to the subscribers. I don't want to
reinitialized everything as this would bring the subscriber database
offline during the sync. I tried just creating the SP on the
publisher, but it did not pass down.
1) How do I add a single SP without reinitializing?
2) How do I alter an SP and pass it down without reinitializing?
I'm using SQL2005 SP2.
Thanks,
Peter Cwik
On Dec 20, 12:15 pm, PeterCwik <pjc...@.gmail.com> wrote:
> I have stored procedures that I want to add to the publication and
> have them passed down to the subscribers. I don't want to
> reinitialized everything as this would bring the subscriber database
> offline during the sync. I tried just creating the SP on the
> publisher, but it did not pass down.
> 1) How do I add a single SP without reinitializing?
> 2) How do I alter an SP and pass it down without reinitializing?
> I'm using SQL2005 SP2.
> Thanks,
> Peter Cwik
Sorry--I'm using Transaction replication
|||Try this,
Add the article with sp_addarticle and specify @.type = 'proc schema only' &
@.force_invalidate_snapshot = 1
Add subscription with sp_addsubscription, this may throw error Msg 14100 if
your publication is setup with @.sync_method= concurrent, solution is to set
the publication with @.sync_method='database snapshot' (only applicable to SQL
Server 2005 SP2) or workaround is to bypass this check by passing this
parameter @.reserved = N'internal' to sp_addsubscription
"PeterCwik" wrote:

> On Dec 20, 12:15 pm, PeterCwik <pjc...@.gmail.com> wrote:
> Sorry--I'm using Transaction replication
>
|||On Dec 25 2007, 3:32Xpm, Manoj <Ma...@.discussions.microsoft.com>
wrote:
> Try this,
> Add the article with sp_addarticle and specify @.type = X'proc schema only' &
> @.force_invalidate_snapshot = 1
> Add subscription with sp_addsubscription, this may throw error Msg 14100 if
> your publication is setup with @.sync_method= concurrent, solution is to set
> the publication with @.sync_method='database snapshot' (only applicable to SQL
> Server 2005 SP2) or workaround is to bypass this check by passing this
> parameter @.reserved = N'internal' to sp_addsubscription
>
> "PeterCwik" wrote:
>
>
> - Show quoted text -
Well that sort of helps. I know it may seem like an obvious question
but, what does @.force_invalidate_snapshot = 1 really do? What are the
implications of invalidating a snapshot?
Thanks,
Peter Cwik
|||On Jan 2, 12:49Xpm, PeterCwik <pjc...@.gmail.com> wrote:
> On Dec 25 2007, 3:32Xpm, Manoj <Ma...@.discussions.microsoft.com>
> wrote:
>
>
>
>
>
>
> Well that sort of helps. XI know it may seem like an obvious question
> but, what does @.force_invalidate_snapshot = 1 really do? XWhat are the
> implications of invalidating a snapshot?
> Thanks,
> Peter Cwik- Hide quoted text -
> - Show quoted text -
I think I may have answered my own question...I just need someone to
validate this.
1. Transactional replication is setup and working fine
2. The publisher is the Prod database and subscriber is Reporting
database
3. Power users are allowed to add stored procedures to Reporting
database so now the two database are close copies but not completely.
4. My concern was that a resync would kill all the user created
objects in the Reporting database
5. It appears this is not so. The terms Synchronize, Snapshot and
Reinitialize are very different and have different meanings, though
even in this forum they are used incorrectly interchangeably.
6. If a new object is created (table, sp, view, etc.) a new snapshot
must be created. Creating a new snapshot does not delete data in the
Reporting database.
7. If continuous synchronization is used, any "new" objects that were
included in the new snapshot will be replicated to the Reporting
database. If continuous synchronization is not used, then "Start"
synchrozination must be chosen.
8. In 2005 changes to objects in existing subscriptions will
automatically be pushed from Prod to Reporting.
9. The ONLY time data in the Reporting database will be whiped out
and a fresh copy brought down from the Prod server is when a
Reinitialize is run.
10. Reinitialize looks at a Snapshot and pushes data and objects from
Prod to Reporting.
11. Only a Generate a Snapshot and Sychronize is needed to move
additional objects from Prod to Reporting. Reinitialize in NOT
required for the "additional" objects.
Hilary, does this sound right?
Thanks,
Peter Cwik

Tuesday, March 6, 2012

Add leading zero to field value via SP

Hi All,

I want to add a leading zero to a field based on a param that I create on the fly in my stored proc. I have a @.month which is created from my datetime param @.date.

@.Month needs to be char(2) but if the month is inputted as '04' I get '4 ' in the table (note the space after 4)

How can I add a leading zero to this field?
Set @.Year = right('0',1)year(@.Date) is spitting it's toys out.

Thanks,
Brett

prepend a '0' char to the front of it and take RIGHT('0'+yourString,2)

add leading zero to date column?

Hello All,

None of the solutions I have found in the archives seem to solve my
problem. I have a date column in my tables (stored as a char(10))
which I would like to append a leading zero to for those dates that
start with 9 or lower.

Any ideas?

Thanks,

MikeMyk wrote:
> Hello All,
> None of the solutions I have found in the archives seem to solve my
> problem. I have a date column in my tables (stored as a char(10))

No, you have a char() column in your table that you store a string in
that is supposed to represent a date. It may or may not.

> which I would like to append a leading zero to for those dates that
> start with 9 or lower.

I'd recommend you actually make the column a date data type since that's
what it is for, but you can append like this:

CASE WHEN LEFT(YourColumn, 1) BETWEEN '1' AND '9' THEN '0' + YourColumn END

Now, there are tons of things wrong with what I just wrote in that it
assumes the first column will always be 0-9, which, given your specs
above, isn't garunteed. It assumes that there are no spaces in the first
character position. It assumes that if there is a 1 through 9 that the
length of that string plus the new '0' is still within 10 chars. All in
all, it is a crappy solution.

Make your data column type match your data and this problem goes away.

Zach

> Any ideas?
> Thanks,
> Mike|||Database Modeling Sin # 58 - Confusing Data Presentation with Data
Representation.

If you can't convert the column to its proper datatype (highly , greatly,
strongly, and "i mean it dude!" recommended),
add the following to a trigger on the table to insure that the format of the
string is consistent.

update mytable
set DateLikeCharColumn = IsNull( convert( char(10) , convert( datetime,
DateLikeCharColumn ) , 110 ) , "" )
from mytable
join inserted on mytable.keycolumn = inserted.keycolumn

(substitute 110 with what ever style you need)

"nib" <individual_news@.nibsworld.com> wrote in message
news:304ot7F2qrbinU1@.uni-berlin.de...
> Myk wrote:
>> Hello All,
>>
>> None of the solutions I have found in the archives seem to solve my
>> problem. I have a date column in my tables (stored as a char(10))
> No, you have a char() column in your table that you store a string in that
> is supposed to represent a date. It may or may not.
>> which I would like to append a leading zero to for those dates that
>> start with 9 or lower.
> I'd recommend you actually make the column a date data type since that's
> what it is for, but you can append like this:
> CASE WHEN LEFT(YourColumn, 1) BETWEEN '1' AND '9' THEN '0' + YourColumn
> END
> Now, there are tons of things wrong with what I just wrote in that it
> assumes the first column will always be 0-9, which, given your specs
> above, isn't garunteed. It assumes that there are no spaces in the first
> character position. It assumes that if there is a 1 through 9 that the
> length of that string plus the new '0' is still within 10 chars. All in
> all, it is a crappy solution.
> Make your data column type match your data and this problem goes away.
> Zach
>>
>> Any ideas?
>>
>> Thanks,
>>
>> Mike
>

Friday, February 24, 2012

add columns from two queries

Hello all

im trying to add the the columns resulted from one query to other columns resulted from other query in a stored procedure

like this

select x1,x2,x3 from Table1
select x4,x5 from table

i want to put it like this

x1 x2 x3 x4 x5

:)

i really need this helpp

thank youuuYou need to use a join. From what you've posted I can't tell which fields relate the records in one table to the records in another. But it would look something like this:


Select Table1.x1,Table1.x2,Table1.x3, Table.X4, Table.X5
FROM Table1 inner join Table on (Table1.JoinField=Table.OtherJoinField)

Add column with variable name

HI!

Im trying to use an stored procedure to add a new column.
The problem is that the column name is stored in a variable, and I get syntax error.

Here is my code:

CREATE PROCEDURE test AS
declare @.colname as varchar(10)

set @.colname = 'new_col'

alter table prueba add @.colname int

And here is the error I get:
Error 170: Line 6 Incorrect syntax near '@.colname'

Any idea?Originally posted by soy_lore_lore
HI!

Im trying to use an stored procedure to add a new column.
The problem is that the column name is stored in a variable, and I get syntax error.

Here is my code:

CREATE PROCEDURE test AS
declare @.colname as varchar(10)

set @.colname = 'new_col'

alter table prueba add @.colname int

And here is the error I get:
Error 170: Line 6 Incorrect syntax near '@.colname'

Any idea?

Try this:

exec('alter table prueba add '+@.colname+' int')|||Originally posted by snail
Try this:

exec('alter table prueba add '+@.colname+' int')

THANKS!

Add Column Values To the Bottom Of the Row By Condition

Hi
I am getting some results from stored procedure.
Name Value1 Value2 Value3 Total
North 1 2 3 6
North 4 5 6 15
South 5 6 7 18
Footer (North) 5 7 9 21
Footer(South) 5 6 7 18
I displaying footer for each group and i want to display Total value of
the column for that respective group Name.Is therea way to add all
column value depending up on the condition.
For North add only 2 rows.
Can any one help on this issue.
Thankstry sum in the group
=Sum(field!abc.value, "group1") you can have scope in the sum.
Amarnath
"vamsi" wrote:
> Hi
> I am getting some results from stored procedure.
> Name Value1 Value2 Value3 Total
> North 1 2 3 6
> North 4 5 6 15
> South 5 6 7 18
> Footer (North) 5 7 9 21
> Footer(South) 5 6 7 18
>
> I displaying footer for each group and i want to display Total value of
> the column for that respective group Name.Is therea way to add all
> column value depending up on the condition.
> For North add only 2 rows.
> Can any one help on this issue.
> Thanks
>

Thursday, February 16, 2012

Add a new column in temp table in sp cannot be used immediately

I created a temp table in my stored procedure and then added a new identity column to it.

However, I am not able to use this new column immediately, it says column not found.

SELECT * INTO #temp FROM table_name

ALTER TABLE #temp ADD __Identity int IDENTITY(1,1)

SELECT * FROM #temp WHERE __Identity >= 10

Here __Identity column is not found. If I just did SELECT * FROM #temp without the where clause, the final result does have the __Identity column correctly added to the table. Why can't I query it?

Thanks!

That is a good question. I originally had the problem, but then it just went away and I can't get it to come back again. From Management Studio, try placing a "GO" between each statement. That's what I did to get the problem to go away and can't get it to come back again. Are you issuing these to SQL Server from 3 different command objects on the same connection?

|||

All these statements are in one stored procedure, so "GO" is not going to work. Thanks!

|||

Hi,

Based on my understanding ,these three statements will be pre-checked at the same time, and then each statement will be executed. The third statement can't pass the check because the first two statements has't been executed.

I suggest you to write seperate these two SP, one is for creating a column, another is for query.

create proc CreateColumnas ALTER TABLE table ADD _identityint IDENTITY(1,1) go --For the CreatingColumn exec procfinal --execute the CreateColumn SP.create proc QueryResultas select *from table where _identity>'10'goexec QueryResult
Thanks.

Monday, February 13, 2012

Add a column to table from stored proc

Hello all,

I want to alter a table in a stored proc to add a column dynamically. I am passing the name of the new column to the stored proc param. Does anyone know the syntax for this? Here is the code:

CREATE PROCEDURE procAddNewOptionType

-- new option type parameter

@.OptionName varchar(50)

AS

BEGIN

-- SET NOCOUNT ON added to prevent extra result sets from

-- interfering with SELECT statements.

SET NOCOUNT ON;

-- Insert new option type into list of types

INSERTINTO dbo.tblClientOptionList(strOptionName)VALUES(@.OptionName);

-- alter client options table to add new column passed to proc as @.OptionName

ALTERTABLE dbo.tblClientOptions ADD @.OptionName BIT;

RETURN 1

END

Thx,

Jason

Hi jason,

You'd have to execute the ALTER TABLE statements dynamically since your column depends on the OptionName being a variable.

declare @.sql nvarchar(100)

SET @.sql = 'alter table dbo.tblClientOptions add ' + @.optionName + ' BIT'
EXEC sp_executesql @.sql

Although, you'd have to take note possible permissions priviledge given by your DBA(ie. they might revoke ALTER TABLE permission)

hth|||

Thank you very much. That works perfectly!

Jason

Add a column to table from stored proc

Hello all,

I want to alter a table in a stored proc to add a column dynamically. I am passing the name of the new column to the stored proc param. Does anyone know the syntax for this? Here is the code:

CREATE PROCEDURE procAddNewOptionType

-- new option type parameter

@.OptionName varchar(50)

AS

BEGIN

-- SET NOCOUNT ON added to prevent extra result sets from

-- interfering with SELECT statements.

SET NOCOUNT ON;

-- Insert new option type into list of types

INSERTINTO dbo.tblClientOptionList(strOptionName)VALUES(@.OptionName);

-- alter client options table to add new column passed to proc as @.OptionName

ALTERTABLE dbo.tblClientOptions ADD @.OptionName BIT;

RETURN 1

END

Thx,

Jason

Hi jason,

You'd have to execute the ALTER TABLE statements dynamically since your column depends on the OptionName being a variable.

declare @.sql nvarchar(100)

SET @.sql = 'alter table dbo.tblClientOptions add ' + @.optionName + ' BIT'
EXEC sp_executesql @.sql

Although, you'd have to take note possible permissions priviledge given by your DBA(ie. they might revoke ALTER TABLE permission)

hth|||

Thank you very much. That works perfectly!

Jason

Sunday, February 12, 2012

Ad hoc query running crazy slow.

Hi,
I have a job that execute a stored proc. It was running fine like 3
minutes to finish but a week ago it started to take 4 hours. Its using
ad hoc quries in that stored procedure. I reindex all the tables that
it was using. I check execution plan there was no tabloe scans. I
recompile the stored proc but no use. its sql 2000 with service pack 3
installed on it. Here is the query anyone has any clue what went wrong
suddenly. Link server is working fine.
i am running it like this
exec usp_MO_ActivityTradesBPS 'CORP'
CREATE PROCEDURE dbo.usp_MO_PositionsBPS
@.Load varchar(25) = null,
@.AsOfDate datetime
AS
Set @.Load = '%'
If @.Load is null or @.Load = ''
begin
Set @.Load = '%'
end
If IsNull(@.AsOfDate,'') = ''
Set @.AsOfDate = dbo.fn_BusinessDate(GetDate()-1)
If @.Load = 'SANFRAN'
begin
Set @.Load = '%'
SELECT RTRIM(T.BRANCHCD) + '-' + RTRIM(T.ACCOUNTNR) + '-' +
T.ACCOUNTTYPECD + T.CUSIPNR [key],
RTRIM(T.BRANCHCD) + '-' + RTRIM(T.ACCOUNTNR) + '-' + T.ACCOUNTTYPECD
BRANCHCD, T.TICKERSYMBOL, T.ADPSECURITYNR, T.CUSIPNR,
T.ADPSECURITY1DS, T.TDQUANTITY, T.SECURITYPRICEAM, T.LEDGERBALANCEAM,
T.TDDIVINTAM, T.TDGRCREDITMTDOP7,
T.TDMTDSECFEE, T.MTDREALPLTDOP7, T.TDCUMPL, T.MTDPL, T.MTDNETPL,
T.DAILYNETPL, T.CURRENCYISOCD
FROM BPS_Positions T
WHERE T.BRANCHCD = '001'
and T.BRANCHCD + '-' + T.ACCOUNTNR not in (Select Distinct
SM.Bps_AcctNr
From MO_InvStrategyMap SM
Where SM.Bps_AcctNr is not null)
and (T.TDMTDSECFEE <> 0
or T.TDCOmsnAm <> 0
or T.TDQUANTITY <> 0
or T.MarketValAm <> 0
or T.MTDNETPL <> 0
or T.MTDPL <> 0
or T.LEDGERBAlanceAm <> 0
or T.DAILYNETPL <> 0
or T.TDDivIntAm <> 0
or T.TDGRCREDITMTDOP7 <> 0)
ORDER BY T.BRANCHCD, T.ACCOUNTNR, T.ACCOUNTTYPECD, T.ADPSECURITYNR,
T.CUSIPNR, T.CURRENCYISOCD
end
Else
begin
SELECT AM.Inventory + T.CUSIPNR [Key], rtrim(T.BRANCHCD) + '-' +
rtrim(T.ACCOUNTNR) BRANCHCD, T.TICKERSYMBOL, T.ADPSECURITYNR,
T.CUSIPNR,
T.ADPSECURITY1DS, T.TDQUANTITY, case when T.TDQuantity <> 0
then T.MarketValAm/T.TDQuantity
else T.SecurityPriceAm end as SecurityPriceAm,
T.LEDGERBALANCEAM, T.TDDIVINTAM, T.TDGRCREDITMTDOP7,
T.TDMTDSECFEE, T.MTDREALPLTDOP7, T.TDCUMPL, T.MTDPL, T.MTDNETPL,
T.DAILYNETPL, T.CURRENCYISOCD
FROM BPS_PositionsHistorical T
JOIN MO_InvAccountMap AM
ON T.BRANCHCD + '-' + T.ACCOUNTNR = AM.AccountNr
JOIN (Select Distinct TraderCd
From MO_InvStrategyMap
Where PrimaryRecFl = 1
and (Desk like @.Load
or Category like @.Load
or SubCategory like @.Load
or TraderName like @.Load
or TraderCd like @.Load)) SM
ON SM.TraderCd = AM.Inventory
WHERE T.BusinessDate = @.AsOfDate
and AM.DataSource like 'BPS%'
and (T.TDMTDSECFEE <> 0
or T.TDCOmsnAm <> 0
or T.TDQUANTITY <> 0
or T.MarketValAm <> 0
or T.MTDNETPL <> 0
or T.MTDPL <> 0
or T.LEDGERBAlanceAm <> 0
or T.DAILYNETPL <> 0
or T.TDDivIntAm <> 0
or T.TDGRCREDITMTDOP7 <> 0)
ORDER BY AM.Inventory, T.BRANCHCD, T.ACCOUNTNR, T.ACCOUNTTYPECD,
T.ADPSECURITYNR, T.CUSIPNR, T.CURRENCYISOCD
end
GO
Assuming this is consistently reproduced, a few things you might want to
investigate:
- Do you have the original (3-minute) query plan? If so, what's different
from the current one?
- Looking at the query plan, where are you spending most of your time?
- During execution, are you seeing any resource constraints? E.g. > 5 avg
disk queue length, high avg disk sec/read,
- Are you seeing waits on cxpackets when you run dbcc sqlperf (waitstats)?
Might indicate parallellized queries waiting.
Suggest you dig into the query plan to see where it's spending most of its
time and check to ensure you don't have resource bottlenecks.
joe.
"DARR" <umariqbaldar@.gmail.com> wrote in message
news:1168992585.559292.8530@.s34g2000cwa.googlegrou ps.com...
> Hi,
> I have a job that execute a stored proc. It was running fine like 3
> minutes to finish but a week ago it started to take 4 hours. Its using
> ad hoc quries in that stored procedure. I reindex all the tables that
> it was using. I check execution plan there was no tabloe scans. I
> recompile the stored proc but no use. its sql 2000 with service pack 3
> installed on it. Here is the query anyone has any clue what went wrong
> suddenly. Link server is working fine.
> i am running it like this
> exec usp_MO_ActivityTradesBPS 'CORP'
>
> CREATE PROCEDURE dbo.usp_MO_PositionsBPS
>
> @.Load varchar(25) = null,
> @.AsOfDate datetime
> AS
> Set @.Load = '%'
> If @.Load is null or @.Load = ''
> begin
> Set @.Load = '%'
> end
> If IsNull(@.AsOfDate,'') = ''
> Set @.AsOfDate = dbo.fn_BusinessDate(GetDate()-1)
> If @.Load = 'SANFRAN'
> begin
> Set @.Load = '%'
> SELECT RTRIM(T.BRANCHCD) + '-' + RTRIM(T.ACCOUNTNR) + '-' +
> T.ACCOUNTTYPECD + T.CUSIPNR [key],
> RTRIM(T.BRANCHCD) + '-' + RTRIM(T.ACCOUNTNR) + '-' + T.ACCOUNTTYPECD
> BRANCHCD, T.TICKERSYMBOL, T.ADPSECURITYNR, T.CUSIPNR,
> T.ADPSECURITY1DS, T.TDQUANTITY, T.SECURITYPRICEAM, T.LEDGERBALANCEAM,
> T.TDDIVINTAM, T.TDGRCREDITMTDOP7,
> T.TDMTDSECFEE, T.MTDREALPLTDOP7, T.TDCUMPL, T.MTDPL, T.MTDNETPL,
> T.DAILYNETPL, T.CURRENCYISOCD
> FROM BPS_Positions T
> WHERE T.BRANCHCD = '001'
> and T.BRANCHCD + '-' + T.ACCOUNTNR not in (Select Distinct
> SM.Bps_AcctNr
> From MO_InvStrategyMap SM
> Where SM.Bps_AcctNr is not null)
> and (T.TDMTDSECFEE <> 0
> or T.TDCOmsnAm <> 0
> or T.TDQUANTITY <> 0
> or T.MarketValAm <> 0
> or T.MTDNETPL <> 0
> or T.MTDPL <> 0
> or T.LEDGERBAlanceAm <> 0
> or T.DAILYNETPL <> 0
> or T.TDDivIntAm <> 0
> or T.TDGRCREDITMTDOP7 <> 0)
> ORDER BY T.BRANCHCD, T.ACCOUNTNR, T.ACCOUNTTYPECD, T.ADPSECURITYNR,
> T.CUSIPNR, T.CURRENCYISOCD
> end
> Else
> begin
> SELECT AM.Inventory + T.CUSIPNR [Key], rtrim(T.BRANCHCD) + '-' +
> rtrim(T.ACCOUNTNR) BRANCHCD, T.TICKERSYMBOL, T.ADPSECURITYNR,
> T.CUSIPNR,
> T.ADPSECURITY1DS, T.TDQUANTITY, case when T.TDQuantity <> 0
> then T.MarketValAm/T.TDQuantity
> else T.SecurityPriceAm end as SecurityPriceAm,
> T.LEDGERBALANCEAM, T.TDDIVINTAM, T.TDGRCREDITMTDOP7,
> T.TDMTDSECFEE, T.MTDREALPLTDOP7, T.TDCUMPL, T.MTDPL, T.MTDNETPL,
> T.DAILYNETPL, T.CURRENCYISOCD
> FROM BPS_PositionsHistorical T
> JOIN MO_InvAccountMap AM
> ON T.BRANCHCD + '-' + T.ACCOUNTNR = AM.AccountNr
> JOIN (Select Distinct TraderCd
> From MO_InvStrategyMap
> Where PrimaryRecFl = 1
> and (Desk like @.Load
> or Category like @.Load
> or SubCategory like @.Load
> or TraderName like @.Load
> or TraderCd like @.Load)) SM
> ON SM.TraderCd = AM.Inventory
> WHERE T.BusinessDate = @.AsOfDate
> and AM.DataSource like 'BPS%'
> and (T.TDMTDSECFEE <> 0
> or T.TDCOmsnAm <> 0
> or T.TDQUANTITY <> 0
> or T.MarketValAm <> 0
> or T.MTDNETPL <> 0
> or T.MTDPL <> 0
> or T.LEDGERBAlanceAm <> 0
> or T.DAILYNETPL <> 0
> or T.TDDivIntAm <> 0
> or T.TDGRCREDITMTDOP7 <> 0)
> ORDER BY AM.Inventory, T.BRANCHCD, T.ACCOUNTNR, T.ACCOUNTTYPECD,
> T.ADPSECURITYNR, T.CUSIPNR, T.CURRENCYISOCD
> end
> GO
>