Analysis :: Dynamic Declaration Of Variable In MDX Query?

May 27, 2015

Is there a way to write such a query where we can declare the variable dynamically ? Currently I am using the query as shown below :

declare @pYear_Internal as NVarchar(100)
set @pYear_Internal = [D FISCALPERIOD].[FP CODE].[FP CODE]
WITH
MEMBER MEASURES.[REVENUE] AS [Measures].[TOTAL REVENUE]
SET LAST5YEARS AS STRTOMEMBER(@pYear_Internal).Lag(4) : STRTOMEMBER(@pYear_Internal)

[code]....

While executing the above query, getting the error - Query (1, 9) Parser: The syntax for '@pYear_Internal' is incorrect.  It looks like it doesn't recognize DECLARE keyword as it does with SQL queries.  I just want a query that runs directly against the server. 

View 3 Replies


ADVERTISEMENT

Dynamic Variable Used In Decimal Declaration

Jun 18, 2007

I'm wondering if there's a way to pass a variable to assigning a decimal datatype;

declare @intPrecision int

set @intPrecision = 3

declare @decVariable decimal(38, @intPrecision)

I've basically been given the task by my mentor to create a script to round a decimal to a given number of decimal places.

ie; 1234.56789; 2 dp => 1234.57 and not 1234.57000

Any advice would be great.

View 1 Replies View Related

Variable Declaration In A Stored Procedure Query

Feb 15, 2002

I have the following lines embedded in a stored procedure

---
----
----
select @querystr = "select @lkinpos = pos_lkin_pos from "+@database+" where pos_clnt_id = "+str(@clntid)+" and pos_isin ="+"'"+ @isinno+"'"

print @querystr
exec(@querystr)
---
---
---

When i execute the above stored procedure, it returns an error as follows:

Server: Msg 137, Level 15, State 1, Line 1
Must declare the variable '@lkinpos'.

When i see the print @querystr statement, it returns the query str as follows:

select @lkinpos = pos_lkin_pos from nsdldpm..pos_mstr where pos_clnt_id = 10000045 and pos_isin ='ine227a01011'

This when executed independently, gives me the required output.

Can anybody solve this for me?
Thanks in advance

View 1 Replies View Related

Variable Declaration

Mar 29, 2004

hi,

i am new to sql server...

i have used @ symbol for declaring local variables in stored procedure....
The symbol @@ is there....where to use and what is the purpose of using that symbol...

could anyone tell...

thanks

View 1 Replies View Related

Dynamic Cursor - Sorting In Declaration

Oct 6, 2006

Hello everybody!I have a small table "ABC" like this:id_position | value---------------------------1 | 112 | 223 | 33I try to use a dynamic cursor as below.When the statement "order by id_position" in declare part of the cursor_abcis omitted - cursor work as it should.But when the statement "order by id_position" is used, cursor behave asstatic one.What's the matter, does anybody know?Code:declare @id_position as int, @value as intDECLARE cursor_abc CURSORFORselect id_position, value from abcorder by id_positionset nocount onopen cursor_abcFETCH NEXT FROM cursor_abcINTO @id_position, @valueWHILE @@FETCH_STATUS = 0BEGINprint @id_positionprint @valueprint '----------------------------'update abc set value=666 --next reading should give value=666FETCH NEXT FROM cursor_abcINTO @id_position, @valueENDCLOSE cursor_abcDEALLOCATE cursor_abcGORegardsLucas

View 2 Replies View Related

Declaration Of Record Variable

Oct 10, 2006

Can someone say how to declare a record like variable in MSSQL-2000 Like:
mr_rec record of variables a int, b char(20), c datetime? I could not find any examples on BOL. I want to use this in a stored procedure create script.

Thanks, Vinnie

View 1 Replies View Related

T-SQL (SS2K8) :: Variable Declaration In A Loop

Jul 2, 2015

I am reviewing some code we have inherited (riddled with multiple nested cursors) and in the process of re-writing some of the code. I came across this and it has me puzzled.

As I understand it, if you declare a variable and then try to re-declare a variable of the same name an error is generated. If I do this inside a While loop this does not seem to be the case. What ever is assigned is kept and just added to (in the case of a table variable)

I understand things are in scope for the batch currently running but I would expect an error to return (example 1 and 2)

--Table var declaration in loop
SET NOCOUNT ON
DECLARE @looper INT = 0
WHILE @looper <= 10
BEGIN
DECLARE @ATable TABLE ( somenumber INT )

[Code] ....

View 4 Replies View Related

Variable Assignment In Cursor Declaration

Jul 5, 2006

Hi,

here is the code segment below;
...
DECLARE find_dates CURSOR FOR
SELECT @SQL = 'select DISTINC(Dates) from ['+@name+'].dbo.['+@t_name+'] order by [Dates] ASC'
EXEC (@SQL)

but it gives error, variable assignment is not allowed in a cursor declaration. I need to use dynamic SQL , the only way to access all the dbs and their tables inside. Please help.

thanks

View 8 Replies View Related

Need Help Understanding A Stored Procedure Variable Declaration

Oct 25, 2007

I've been curious why some variables don't need to be declared with a value type in a stored procedure. Please see the example below in the bolded area. The stored procedure works fine - nothing is wrong with it, but I just wanted an explanation on why and when is a value type not needed for a variable.

CREATE PROCEDURE [DBO].[EmailRpt]
(
@TagDest char(2) = NULL,
@DateWanted smalldatetime = NULL,
@CustName varchar(64) = NULL,
@AcctID AcctId = NULL,
@ContactPhn phone = NULL,
@CustAddr address = NULL,
@City city,
@CrossSt varchar(50) ,
@Access varchar(50) = NULL,
@Activity tinyint,
)
AS
DECLARE @String as varchar(2000),
@Header as varchar(200),
@MailBox as varchar(50),
@ActivityName as Name,
@Return as int,
@UserName as Name

View 5 Replies View Related

Analysis :: Dynamic MDX Query For YearToDate Total

Jun 17, 2015

I have created cube. 1 fact table and few dimensions including dimDate

I need to create a calculated member for variance.

Variance = SUM([Measures].[Amt]) starting from financial year beginning(2015-04-01 to current date) -
SUM([Measures].[Amt]) for the same period last year(2014-04-01 to current date last year)

How can I create this calculated member?

View 5 Replies View Related

Can We Set Result Of Dynamic Query To Variable?

Dec 13, 2007

Is this possible as given below

declare @Qry as varchar(8000)
declare @Cnt as int
begin
set @Qry = 'select @Cnt=count(*) from ' + @TableName
exec @Qry
select @Cnt
end


But its not working....

can any one help me out in this.....

Thnx

Parag

View 1 Replies View Related

Is It Possible To Store The Result Of A Dynamic Query In A Local Variable

Dec 19, 2000

I have a dynamic query which returns me a result and I want to capture that value to make further use of it in the same code. Is that possible??
exec ('select col_nm from table_name'). i want the result of this query to be captured.
DP

View 4 Replies View Related

Assing Dynamic Query Result To A Local Variable....

Jul 9, 2004

Hi:

Is there a way to assign a dynamic query result to a local variable?

declre @sqlString nvarchar(4000),
@minEventDate datetime,
@databaseName varchar(25)
selct @databaseName = 'customer_12345'
(actually, a cursor loop will assign the database name dynamically, here just to simplify the situation)

select @sqlString =
'select ' + @minEventDate + '= (select min(eventDate) from ' + @databaseName + '.dbo.tblABC)'
exec sql_executesql @sqlString
print '@minEventDate: ' + cast(@minEventDate as varchar(19))

Though the select min(eventDate) from customer_12345.dbo.tblABC
returns a date, ex. '02/01/2004 12:35 pm', however, the printed @minEventDate is always with Null value. It mean, the value was never correctly assigned to the local variable.

As an alternate way, I am using temp table to insert it with the query result and then assign to the local variable. Since I have many local variables to try to get the min, max, count for around 10 fields, perfer a way to direct assign to the local variable instead of 10 temp tables.

thanks
-D

View 4 Replies View Related

SQL Server 2012 :: Table Variable In Dynamic Query?

Jul 2, 2015

I have started working with dynamic queries recently. I am using a table variable and need to add a join in query dynamically.

For Eg- @TableVariable

SET @query_from = @query_from + CHAR(10) + ' JOIN @TableVariable on ABC.ID = @TableVariable.ID '

BUt it gives an error that @TableVariable must be declared

View 8 Replies View Related

Dynamic Query, Local Cursor Variable And Global Cursors

Oct 3, 2006

Hi all.



I am stuck in a bit of a conundrum for quite a while now, and I hope someone here will help me figure this one out.



So, first things first: let me explain what I need to do. I am
designing a web application that will allow users to consult info
available in a SQL2000 database. The user will enter the search
criterea, and hopefully the web page will show matching results.



The problem is the results shown aren't available per se in the DB, I
need to process the data a bit. I decided to do so on the SQL Server
side, though the use of cursors. So, when a user defines his search
criteria, I run a stored procedure that begins by building a dynamic
sql query and creating a cursor for it. I used a global cursor in order
to do so. It looked something like this:



SET @sqlQuery = ... (build the dinamic sql query)

SET @cursorQuery = 'DECLARE myCursor CURSOR GLOBAL FAST_FORWARD FOR ' + @sqlQuery

EXEC @cursorQuery

OPEN myCursor

FETCH NEXT FROM myCursor INTO ...

CLOSE myCursor

DEALLOCATE myCursor



This works fine, if there's only one instance of the
stored procedure running at a time. Should another user connect to the
site and run a search while someone's at it, it'll fail due to the
atempt to create a cursor with the same name.



My first thought was to make the cursor name unique, which led me to:

...

SET @cursorName = 'myCursor' + @uniqueUserID

SET @cursorQuery = 'DECLARE '+ @cursorName + 'CURSOR FAST_FORWARD FOR ' + @sqlQuery

EXEC @cursorQuery

...



The problem with this is that I can't do a FETCH NEXT FROM @cursorName since
@cursorName is a char variable holding the cursor name, and not a
cursor variable. So to enforce this unique name method the only option
I have is to keep creating dynamic sql queries and exucting them. And
this makes the sp a bitch to develop and maintain, and I'm guessing it
doesn't make it very performant.



So I moved on to my second idea: local cursor variables. The problem with
this is that if I create a local cursor variable by executing a dynamic
query, I can't extract it from the EXEC (or sp_executesql) context, as
it offers no output variable.


I guess my concrete questions are:


Is it possible to execute a dynamic sql query and extract a (cursor) variable from it?Is it possible to populate a local cursor variable with a global cursor, by providing the global cursor's name?Can I create a local cursor variable for a dynamic sql query? How?



Anybody sees another way arround this?Thanks in advance,

Carlos

View 3 Replies View Related

Storing The Result In A Variable Resulting From A Dynamic TSQL Query

Aug 30, 2007

Hello all:

Here is a sample query:



DECLARE @KEYID NVARCHAR (50) ; SET @KEYID = '1074958'

DECLARE @ENTITY NVARCHAR (100); SET @ENTITY = 'HouseDimension'



DECLARE @KeyCol NVARCHAR(50);

SET @KeyCol = (SELECT LEFT(@ENTITY, (SELECT CHARINDEX( 'DIM', @ENTITY) -1)) )+ 'Key'


DECLARE @KeyValue NVARCHAR (1000)


SET @KeyValue = 'SELECT '+ @KeyCol + ' FROM HouseManagementFact WHERE HouseKey = ' + @KEYID +

' GROUP BY ' + @KeyCol + ' HAVING SUM(TotalClaimCount) > 0 OR SUM(HouseCount) > 0 '



The value resulting from Executing @KeyValue is an integer.

I want to store this value in a new variable say @VAR2

When I do this

DECLARE @VAR2 INT
SET @VAR2 = execute sp_executesql @KeyValue

its giving me an error.


can somebody let me know the correct form of storing the value resulting from @KeyValue in some variable ?

View 3 Replies View Related

Analysis :: Dynamic MDX - Select From 2 Cubes

Sep 2, 2015

I am trying to select from 2 cubes. in one condition - select .. From CubeX, and in sec Condition Select .. From CubeY.

I tried to put the name of the Cube as parameter:
SELECT ...
FROM @CurrentCube

in ssrs source and i got the message:
------------------------------
Failed to parse the query to detect if it is MDX or DMX. Error: 'Query (148, 6) Parser: The syntax for '@CurrentCube' is incorrect.' (MDXQueryGenerator)
------------------------------

Also tried to get the name of the Cube as Member (I have a property with the name of the cube),and than using the member to the select :

WITH MEMBER [CurrentCube] AS
...[dim name].CURRENTMEMBER.PROPERTIES("Cube")
SELECT ...
FROM [CurrentCube]

It didnt work too.. Is it Possible at all make the Cube-name dynamic?!

View 5 Replies View Related

Analysis :: Dynamic Calculated Measure In MDX

May 8, 2015

 I have a dimension called as DIM1 which has list of all measures and has an attribute called as ATTRMDX Formula. The formula will be like

([DIM1].[ATTR Measure Code].&[M1],[Measures].[ATTR MEASURE VALUE])+([DIM1].[ATTR Measure Code].&[M2],[Measures].[ATTR MEASURE VALUE]).

I want to pass this formula to a calculated measure as given below -

MEMBER [Measures].[FormMeasure] as ([Measure].[ATTRMDX Formula].currentmember.MEMBERVALUE)

but I get the string value itself as output, but when I put the formula as a string in the calculated measure I obtain the value.

View 2 Replies View Related

Dynamic Connection String For Analysis Services

Jun 29, 2006

I have a package where I need a dynamic connection string for an Analysis Services connection manager.

I have implemented this successfully for a Text data source, and a SQL data source, but the same approach does not seem to be working for an AS connection.

I set some expressions for the AS connection manager (ServerName, InitialCatalog, even the entire ConnectionString itself), but they don't take. I don't get any errors, but the task processes the cubes for the AS connection as it was established at run time. The design time connection string changes don't appear to get evaluated. This seems to be an issue only for AS connections.

Let me know if you have any ideas - thanks.



View 2 Replies View Related

Analysis :: SSIS Dynamic Database Creation

Jul 31, 2015

I have a requirement where in i need to create a Database dynamically in SSIS, Database name is given in table.

View 3 Replies View Related

Analysis :: Dynamic Default Values For Parameter

Nov 11, 2015

I am trying to write a query for the default values for month, and I am stuck in bringing out only the parameter values, the query I have , brings back the month on row and value on column, and I am trying to get the value out. and will ssrs accept it as a valid expression for a default value

WITH 
MEMBER
[MEASURES].[PARAMETERVALUE]
AS
[Account].[Month Short Name].CURRENTMEMBER.UNIQUENAME

[Code] .....

I tried using the exp

=Parameters!MONTH.Value(0)

so as to return the first parameter in the parameter dataset , but i have the error the expression that ref the parameter MONTH does not exists in the parameter collection.

View 2 Replies View Related

Analysis :: Dynamic Measure Value Based Upon Role / Department

Sep 28, 2015

I have an issue related to SSAS security. We have an SSAS multidimensional cube which needs 3 types of security:

- Access to the entire cube => OK, based upon a role
- Restricted access to one department (= dimension) => OK, based upon a role
- Access to the entire cube, but with dynamic security on 2 measures.

Let's say, we have 2 departments (food and non-food). Users within food are allowed to see sales and pieces from the food department, but not from the non-food department. 

It is not an option to restrict access to the non-food department because there are other measure which they have access to. I tried cell security, but this is very slow and generates multiple empty rows on my selections.

View 3 Replies View Related

Analysis :: Dynamic KPI Goal - Derive From Source Database

Jul 14, 2015

I have a requirement to make all of my KPI goals configurable by the end user - I would like to add the data to my datawarehouse so that it is updated in the cube whenever the cube is processed. I'm thinking I will need a table for each KPI that includes two columns (I will be setting goal by year):

Year
Value

In my cube I then create a measure group for each KPI (for some I will add a calculations to break down the yearly goal to lower levels of detail).I will add each measure to my Dimension Usage and relate to each of my time dimensions at the Year level.I currently have around a dozen KPIs - my above approach seems a bit messy i.e. requiring a table and measure group for each KPI (I guess I could at least put them all into one table in my relational db). 

View 2 Replies View Related

Analysis :: Tabular Dynamic Security With Multiple Values

Aug 6, 2015

It seems simple but I'm not able to make it works. I've got a fact table with sites (DimImplantation) with allowed users (DimDroit) :

1 user can have access to many sites. I've tried these codes but only one worked and only in case where the user had only one site :

a) =DimImplantation[DimImplantation_ID]= LOOKUPVALUE (DimDroit[DimImplantation_ID]; DimDroit[Utilisateur];USERNAME() ) ==> worked for 1user with 1 site

b) =DimImplantation[DimImplantation_ID]= LOOKUPVALUE (DimDroit[DimImplantation_ID]; DimDroit[Utilisateur];USERNAME(); DimDroit[DimImplantation_ID];DimImplantation[DimImplantation_ID] ) ==> doesn't work and says 'not able to to identifie the value of DimImplantation[DimImplantation_ID]
in the current context.

c) CALCULATE(VALUES(DimDroit[DimImplantation_ID], SUMMARIZE('DimDroit',DimDroit[Utilisateur]), DimDroit[Utilisateur]=USERNAME()) ==> version for  SQL2012. I've had 'End of input reached'.

View 3 Replies View Related

Analysis :: DAX - Dynamic Masking Of Information Based On Role Security

Oct 2, 2015

I have a business requirement to build a tabular data model, where I need to mask information of other Agents from a given Agent but I still need to show the overall sales of the given product. 

For eg: IF an Agent is in APAC region he should see APAC region sales and also should be able see the sales of the same product in other region without knowing region specific break down.

For Agent  "Tom" in APAC region, the numbers will look like this
APAC_Sales = 100,000
Other_Sales = 500,000

And if "John" is in NA region, then the number will look like this for him

NA_Sales     = 200,000
Other_Sales = 400,000

I wanted to create "Roles" based on the Region, so all the agents belong to "APAC" region will have same view as Tom and "NA" region agents will have John's view.

View 2 Replies View Related

Analysis :: Which Data Type To Use For Variable Values

Aug 19, 2015

I am trying to find what datatype I can use for variable values like below in a column

E.g. column which we get

10000.10
100
180.34
98203710231.34

From the above example, you can see some of the values contains no decimal and with decimal

Also we cant say whether the decimal comes after the 5th number or 10th number. Any other datatype to capture this values. If not last option is to give varchar2.

View 3 Replies View Related

How To Dynamic Set The Variable Value

Apr 1, 2008



In the old DTS package, we can use Active-x script to set the variable value:

DTSGlobalVariables("MessageData").Value = "This is a test"

How do we do the same thing on the SSIS?

I am under the "control Flow" tab.

Thanks.

View 11 Replies View Related

Analysis :: SSAS Tabular - Dynamic Security Roles - Mixing Together DAX Filters

Oct 10, 2015

I have two different roles, each one with a dax filter. One is for filtering users that access by Excel, and other for filtering users that access by Reporting Services, respectively:

=CONTAINS(FILTER(V_FILTRO_C;V_FILTRO_C[IDPerfilGrupo]<>7);V_FILTRO_C[iCursoCod];[SK_CURSO];V_D05_DIM_UTIL[DSC_LOGIN_USER];RIGHT(USERNAME();LEN(USERNAME())-SEARCH("";USERNAME())))
=CONTAINS(FILTER(V_FILTRO_C;V_FILTRO_C[IDPerfilGrupo]<>7);V_FILTRO_C[iCursoCod];[SK_CURSO];V_FILTRO_C[IDUtilizador];VALUE(CUSTOMDATA()))

To create only one role that serves Excel and Reporting Services users, is it viable to use only the || (OR) operator?, is there any other regard i should take?

View 2 Replies View Related

Analysis :: Dynamic Values In XMLA To Incrementally Update Cube Processing

Nov 10, 2015

I am trying to incrementally update a Cube to get near real time data for the end users. Currently we have a Sql server agent Job that does a FullProcess on the Cube. The Cube consists of a single Measure group which is simply one named query containing inner joins of all the dimensions and fact tables in the underlying relational database. The end users have a lot to upload during the day and they would like us to refresh the cube (near real time) to ensure the adjustments are loaded so that they could reconcile their daily PnLs. We have a MeasureId added which is an auto increment column in the Measures table.

I am trying to schedule the below XMLA query in Sql server agent Job and schedule it to run every 15mins or even less (if possible). However it seems to be not working and keep throwing all sorts of errors.

DECLARE @LastMeasureId AS INT, @myXMLA nvarchar(max)
SELECT @LastMeasureId = "[Measures].[Maximum Measures Id]" FROM
OpenRowset(
'MSOLAP',
'DATA SOURCE=L68F728326574; Initial Catalog=GMDR;',
'SELECT NON EMPTY {[Measures].[Maximum Measures Id]} ON COLUMNS FROM [GMDR]');

[Code] ....

View 2 Replies View Related

Analysis :: Dynamic Set Needed For Last 12 Months Based On Current Month Selected By User

Sep 30, 2015

I need to create a set so that when a user selects a month in filter (say 201506) then it should give me a list of months from 201406 to 201506. Any appropriate MDX query.

View 7 Replies View Related

How Do I Make The Name Of A Variable Dynamic?

Oct 4, 2006

Hi guys, I have the following store procedure:PROCEDURE dbo.AddSearchColumn (@A1, @A2. @A3, @A4, @A5) ASDeclare @cElements cursor,@DocNum varchar(100)BEGIN    Set @cElements = cursor for select FirstNaname rom dbo.DocTable1open @cElements    fetch NEXT from @cElements into @DocNumwhile (@@FETCH_STATUS = 0) begin        if (@DocNum==@A1 //Here is what I need to do: I want use @A1 at the first loop step, @A2 at the second, and so on.......                            // @A1, @A2 are the parameters in inputendENDclose @cElementsDEALLOCATE @cElements I hope my explanation is clear.Please, give some hints.Thanks for your time,Christian Malatesti 

View 7 Replies View Related

Stuffing Dynamic Sql Value Into A Variable?

Jun 12, 2002

Ok, I have a table with several column all labeled, column1, column2, etc. I need to loop through them so I have this statement which will loop through and get the first value, then go to colun2, etc

declare @score int
declare @stm nchar(500)
set @score=0
While @score<=50

Begin
Set @score=@score+1
set @stm='select column' + rtrim(convert(char(2),@score))+' from tablename'
exec sp_executesql @stm
if @score>50
Break
else
COntinue
end

My question is, how can I stuff this value from the dynamic sql into a variable such as:

set @newvalue='exec sp_executesql @stm '

Thanks,
Eddie

View 2 Replies View Related

Dynamic/variable Database Name

Oct 8, 2004

Hi guys

I have a trigger which retrieves database names from a table.
I need to use this retrieved database name in another sql insert statement as a variable
e.g. set @mydbname = Select .... from.. (to get the database name)
then..
insert into @mydbname.dbo.emplTable

At the moment it reads @mydbname as the string "@mydbname" not the value the variable holds

I need the database name as a variable because i have to write to the correct database (there are 15)
Any help appreciated

Rowan

View 2 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved