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,
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
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)
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.
Hi,I am new to SQL. Please bear with me and allow me to ask a dumbquestion.I am debugging a stored procedure (written in Trans-SQL), and I foundthat the SQL analyzer that I use doesn't have a debugger. All I cando it is execute a block of code and see what is going on in aninteraction seesion of the SQL analyzer. I would need to declare somevariable to hold values of the previous query in the interactivesession.I understand that this can be easily done in a stored procedure viathe Declare command (e.g., Delcare @order_no int). Is similarfunctionality exists in an interaction session of the SQL analyzer?If so, what is the command. Please advise.Thank you very much for the help.Alex
I have a dts package that currently uses a dynamic properties task to set the values of global variables. Each variable is based on the value of a query to the database.
I am in the process of migrating this dts package to SSIS but cannot find an equivalent function. I have looked at property expressions but cannot get this working the same way.
I have a SQL Task that updates running totals on a record inserted using a Data Flow Task. The package runs without error, but the actual row does not calculate the running totals. I suspect that the inserted record is not committed until the package completes and the SQL Task is seeing the previous record as the current. Here is the code in the SQL Task:
DECLARE @DV INT; SET @DV = (SELECT MAX(DateValue) FROM tblTG); DECLARE @PV INT; SET @PV = @DV - 1;
I've not been successful in passing a SSIS global variable to a declared parameter, but is it possible to do this:
DECLARE @DV INT; SET @DV = ?; DECLARE @PV INT; SET @PV = @DV - 1;
I have almost 50 references to these parameters in the query so a substitution would be helpful.
Not wishing to derail the other recent thread on loading a local variable, I've posted this query (hee,hee,hee...I kill me) on a separate thread...though I think I am trying to do something similar...that is to build a dynamic select statement, but return a count of the rows it finds/doesn't find to a local variable...using the (amazingly timely) responses above, I tried this:
Note that the local variables @TargetDate and @TLevel are necessary because they are being passed into the procedure as variables....
DECLARE @SQLCmd varchar(256) DECLARE @TargetDate smalldatetime DECLARE @TLevel int DECLARE @n int SET @TargetDate = '2004-05-24' SET @TLevel = 1
SET @SQLCmd = 'SELECT @n = count(*) FROM EventLog WHERE ((CONVERT(varchar(10), [Date], 101) = ''' + CONVERT(varchar(10), @TargetDate, 101) + ''') AND (MsgLevel = ' + CONVERT(varchar(3), @TLevel) + '))' exec (@SQLCmd) if @n > 0 print 'yep' else print 'nope'
and, it's TRYING to work...but apparently the local variable @n is not recognized in the execution of the dynamic statement, as this is the output: Server: Msg 137, Level 15, State 1, Line 1 Must declare the variable '@n'. nope
/*Given*/CREATE TABLE [_T1sub] ([PK] [int] IDENTITY (1, 1) NOT NULL ,[FK] [int] NULL ,[St] [char] (2) NULL ,[Wt] [int] NULL ,CONSTRAINT [PK__T1sub] PRIMARY KEY CLUSTERED([PK]) ON [PRIMARY]) ON [PRIMARY]GOINSERT INTO _T1sub (FK,St,Wt) VALUES (1,'id',10)INSERT INTO _T1sub (FK,St,Wt) VALUES (2,'nv',20)INSERT INTO _T1sub (FK,St,Wt) VALUES (3,'wa',30)/*Is something like the following possible.The point is to change the value of the variableinside the query and use it in the calculated field.This doesn't compile of course, but is therea way to accomplish the same thing?*/DECLARE @ndx intSET @ndx = 1SELECT(a.FK+ (CASE WHEN @ndx > 0THEN (SELECT @ndx = b.WtFROM _T1sub bWHERE b.Wt = a.Wt)ELSE 0 END)) as FKplusWTFROM _T1sub a/*Output would look like this:*/FKplusWT-----------112233/*I know, I can get this output just by addingFK+WT. This is not about that.This is about setting vars inside a query*/thanks, Otto Porter
I am using a local variable to capture datetime and then select records from another table by making use of the above local variable result. But the query is running too slow when I use the local variable
declare @a smalldatetime select @a=last_run_time from job_status where job_des='sample'
SELECT * FROM History WHERE CHANGE_DATE> @a
Instead of the above select statement if I use the below statement it is returning results quickly. Can someone help me in tuning the above query. SELECT * FROM History WHERE CHANGE_DATE> '5/23/2008 6:22:00.000 AM '
History table has columns ( case number, change_date, change_desc). I have two indexes defined on the above table one is on case_number and the other on change_date.I tried using force index but still the query is running slow.
I'm new to SSIS, but have been programming in SQL and ASP.Net for several years. In Visual Studio 2005 Team Edition I've created an SSIS that imports data from a flat file into the database. The original process worked, but did not check the creation date of the import file. I've been asked to add logic that will check that date and verify that it's more recent than a value stored in the database before the import process executes.
Here are the task steps.
[Execute SQL Task] - Run a stored procedure that checks to see if the import is running. If so, stop execution. Otherwise, proceed to the next step.
[Execute SQL Task] - Log an entry to a table indicating that the import has started.
[Script Task] - Get the create date for the current flat file via the reference provided in the file connection manager. Assign that date to a global value (FileCreateDate) and pass it to the next step. This works.
[Execute SQL Task] - Compare this file date with the last file create date in the database. This is where the process breaks. This step depends on 2 variables defined at a global level. The first is FileCreateDate, which gets set in step 3. The second is a global variable named IsNewFile. That variable needs to be set in this step based on what the stored procedure this step calls finds out on the database. Precedence constraints direct behavior to the next proper node according to the TRUE/FALSE setting of IsNewFile.
If IsNewFile is FALSE, direct the process to a step that enters a log entry to a table and conclude execution of the SSIS.
If IsNewFile is TRUE, proceed with the import. There are 5 other subsequent steps that follow this decision, but since those work they are not relevant to this post. Here is the stored procedure that Step 4 is calling. You can see that I experimented with using and not using the OUTPUT option. I really don't care if it returns the value as an OUTPUT or as a field in a recordset. All I care about is getting that value back from the stored procedure so this node in the decision tree can point the flow in the correct direction.
The SSIS package passes the FileCreateDate parameter to this procedure, which then compares that parameter with the date saved in tbl_ImportFileCreateDate.
If the date is newer (or if there is no date), it updates the field in that table and returns a TRUE IsNewFile bit value in a recordset.
Otherwise it returns a FALSE value in the IsNewFile column.
SELECT @CreateDateInTable = FileCreateDate FROM tbl_ImportFileCreateDate WHERE ProcessName = @ProcessName
IF EXISTS (SELECT ProcessName FROM tbl_ImportFileCreateDate WHERE ProcessName = @ProcessName)
BEGIN
-- The process exists in tbl_ImportFileCreateDate. Compare the create dates.
IF (@FileCreateDate > @CreateDateInTable)
BEGIN
-- This is a newer file date. Update the table and set @IsNewFile to TRUE.
UPDATE tbl_ImportFileCreateDate
SET FileCreateDate = @FileCreateDate
WHERE ProcessName = @ProcessName
SET @IsNewFile = 1
END
ELSE
BEGIN
-- The file date is the same or older.
SET @IsNewFile = 0
END
END
ELSE
BEGIN
-- This is a new process for tbl_ImportFileCreateDate. Add a record to that table and set @IsNewFile to TRUE.
INSERT INTO tbl_ImportFileCreateDate (ProcessName, FileCreateDate)
VALUES (@ProcessName, @FileCreateDate)
SET @IsNewFile = 1
END
SELECT @IsNewFile
The relevant Global Variables in the package are defined as follows: Name : Scope : Date Type : Value FileCreateDate : (Package Name) : DateType : 1/1/2000 IsNewFile : (Package Name) : Boolean : False
Setting the properties in the "Execute SQL Task Editor" has been the difficult part of this. Here are the settings.
General Name = Compare Last File Create Date Description = Compares the create date of the current file with a value in tbl_ImportFileCreateDate. TimeOut = 0 CodePage = 1252 ResultSet = None ConnectionType = OLE DB Connection = MyServerDataBase SQLSourceType = Direct input IsQueryStoredProcedure = False BypassPrepare = True
I tried several SQL statements, suspecting it's a syntax issue. All of these failed, but with different error messages. These are the 2 most recent attempts based on posts I was able to locate. SQLStatement = exec ? = dbo.p_CheckImportFileCreateDate 'GL Account Import', ?, ? output SQLStatement = exec p_CheckImportFileCreateDate 'GL Account Import', ?, ? output
Parameter Mapping Variable Name = User::FileCreateDate, Direction = Input, DataType = DATE, Parameter Name = 0, Parameter Size = -1 Variable Name = User::IsNewFile, Direction = Output, DataType = BYTE, Parameter Name = 1, Parameter Size = -1
Result Set is empty. Expressions is empty.
When I run this in debug mode with this SQL statement ... exec ? = dbo.p_CheckImportFileCreateDate 'GL Account Import', ?, ? output ... the following error message appears.
SSIS package "MyPackage.dtsx" starting. Information: 0x4004300A at Import data from flat file to tbl_GLImport, DTS.Pipeline: Validation phase is beginning.
Error: 0xC002F210 at Compare Last File Create Date, Execute SQL Task: Executing the query "exec ? = dbo.p_CheckImportFileCreateDate 'GL Account Import', ?, ? output" failed with the following error: "No value given for one or more required parameters.". Possible failure reasons: Problems with the query, "ResultSet" property not set correctly, parameters not set correctly, or connection not established correctly.
Task failed: Compare Last File Create Date
Warning: 0x80019002 at GLImport: SSIS Warning Code DTS_W_MAXIMUMERRORCOUNTREACHED. The Execution method succeeded, but the number of errors raised (1) reached the maximum allowed (1); resulting in failure. This occurs when the number of errors reaches the number specified in MaximumErrorCount. Change the MaximumErrorCount or fix the errors.
SSIS package "MyPackage.dtsx" finished: Failure.
When the above is run tbl_ImportFileCreateDate does not get updated, so it's failing at some point when calling the procedure.
When I run this in debug mode with this SQL statement ... exec p_CheckImportFileCreateDate 'GL Account Import', ?, ? output ... the tbl_ImportFileCreateDate table gets updated. So I know that data piece is working, but then it fails with the following message.
SSIS package "MyPackage.dtsx" starting. Information: 0x4004300A at Import data from flat file to tbl_GLImport, DTS.Pipeline: Validation phase is beginning.
Error: 0xC001F009 at GLImport: The type of the value being assigned to variable "User::IsNewFile" differs from the current variable type. Variables may not change type during execution. Variable types are strict, except for variables of type Object.
Error: 0xC002F210 at Compare Last File Create Date, Execute SQL Task: Executing the query "exec p_CheckImportFileCreateDate 'GL Account Import', ?, ? output" failed with the following error: "The type of the value being assigned to variable "User::IsNewFile" differs from the current variable type. Variables may not change type during execution. Variable types are strict, except for variables of type Object. ". Possible failure reasons: Problems with the query, "ResultSet" property not set correctly, parameters not set correctly, or connection not established correctly. Task failed: Compare Last File Create Date
Warning: 0x80019002 at GLImport: SSIS Warning Code DTS_W_MAXIMUMERRORCOUNTREACHED. The Execution method succeeded, but the number of errors raised (3) reached the maximum allowed (1); resulting in failure. This occurs when the number of errors reaches the number specified in MaximumErrorCount. Change the MaximumErrorCount or fix the errors.
SSIS package "MyPackage.dtsx" finished: Failure.
The IsNewFile global variable is scoped at the package level and has a Boolean data type, and the Output parameter in the stored procedure is defined as a Bit. So what gives?
The "Possible Failure Reasons" message is so generic that it's been useless to me. And I've been unable to find any examples online that explain how to do what I'm attempting. This would seem to be a very common task. My suspicion is that one or more of the settings in that Execute SQL Task node is bad. Or that there is some cryptic, undocumented reason that this is failing.
Hello,I have a test database with table A containing 10,000 rows and a tableB containing 100,000 rows. Rows in B are "children" of rows in A -each row in A has 10 related rows in B (ie. B has a foreign key to A).Using ODBC I am executing the following loop 10,000 times, expressedbelow in pseudo-code:"select * from A order by a_pk option (fast 1)""fetch from A result set""select * from B where where fk_to_a = 'xxx' order by b_pk option(fast 1)""fetch from B result set" repeated 10 timesIn the above psueod-code 'xxx' is the primary key of the current Arow. NOTE: it is not a mistake that we are repeatedly doing the Aquery and retrieving only the first row.When the queries use fast-forward-only cursors this takes about 2.5minutes. When the queries use dynamic cursors this takes about 1 hour.Does anyone know why the dynamic cursor is killing performance?Because of the SQL Server ODBC driver it is not possible to havenested/multiple fast-forward-only cursors, hence I need to exploreother alternatives.I can only assume that a different query plan is getting constructedfor the dynamic cursor case versus the fast forward only cursor, but Ihave no way of finding out what that query plan is.All help appreciated.Kevin
------------------------------------------------------------------------------------ create procedure globalCursor AS DECLARE abc CURSOR GLOBAL FOR select * from sales OPEN abc
create procedure globalCursorTest AS DECLARE @sdate datetime DECLARE @sperson varchar(15) DECLARE @sregion varchar(15) DECLARE @sales int EXECUTE globalCursor FETCH NEXT FROM abc INTO @sdate, @sperson, @sregion, @sales print @sdate print @sperson print @sregion print @sales ------------------------------------------------------------------------------------
When I execute globalCursorTest using SQL Query Analyser, it says
------------------------------------------------------------------------------------ Server: Msg 16915, Level 16, State 1, Procedure globalCursor, Line 4 A cursor with the name 'abc' already exists. Server: Msg 16905, Level 16, State 1, Procedure globalCursor, Line 5 The cursor is already open. ------------------------------------------------------------------------------------
how to solve this? or in other words, how to simply create the procedure in the database without executing it, as i can see the execution of the first procedure globalCursor causes this problem.
Hello, In NT MS suggests putting global groups into local groups and then assigning object permissions to those local groups in NTFS. I was wondering if this pattern should be followed in SQL server when assigning permissions to integrated login accounts. Is it better to use global groups or local groups?
Can anyone tell me or post a link that says how many global temptables can exist SQL Server 2000? Also, is there a limit to thenumber of local temp tables that can exist?Thanks,Billy
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.
So, I have this idea of a database design I was hoping to get some input on. I usually go through the process of creating a separate column for identity, like an auto-increment integer which serves as a context specific ID that easily can be passed around. However one of the short-comings I've come to realize is that the integer is just that, unique to the context and requires context information to make sense. I'm pounding the idea of creating a separate table whose sole purpose is to provide global (database wide) unique IDs. As such each row in a table can still have an ID but instead of being tied to a specific context it will always make sense within the application. A foreign key constraint can ensure that and a relation. Now, with a global ID which I can create FKs to, I don't have to create a separate table for relations between entities and can have relations through these global IDs and I think that's a good thing because if there are many relations between many entities they don't have to be defined more than once. There is also a single "hub" where all relations fit which will allow me to access most information through some relatively simple joins. My concerns are performance and Linq to SQL implication. I'm worried that Linq to SQL might start pulling an excessive amount of data and I'm worried that the practicality of such a design might hurt the long running of the application development process. But I'm surprisingly interested in what it could mean for a more ubiquitous view of data and tagging. Basically a way of any data to have relations to any other data through this yet simple design decision. If you think this is a good idea or see no particular problem with, please let me know! If you think there's problems with my idea, please motivate your critic but do tell me what I should look out for, or if you know of any better approach to my idea of being able to look at the data through some more common mechanism (which applies to all tables and the entire database mostly from a programming perspective).
I am trying to build a Cursor using an string I am passing into a Stored Procedure. This string I am passing contain my Filters parameter of the query.
Example: Set sSQL = ' And LName like ' + '''S% '''
I am passing sSQL into a stored procedure.
I want to be able to use that when building the cursor.
Something like;
DECLARE SampleCrsr CURSOR FOR SELECT empl, lname FROM stm_employee Where Empl <> NULL + sSQL <-- This does not work.
Or something like this.
The idea is to build something like a Dynamic Cursor. I have done this in Sybase and I think ORACLE. U need help for SQL SEVER.
Do you have any idea how to go around or make it happen???
I'm moving from firebird to MS SQL and have many problems. In firebird, I did many things with FOR...DO..SUSPEND loops. That loop enabled me to scan through the result set, do many calculations and create new result set (defined as variabled in RETURNS part of procedure and actually returned with SUSPEND).
In MS SQL, I can accomplish same thing with cursors. I did read cursors are slow, but I really can't imagine how to perform all this calculations without them (writing software for production planning).
One thing I couldn't do. Declaring cursors with dynamic SQL (in firebird that was for...execute statement(statement) do.
Later I found out about sp_cursoropen and related procedures, but that get's me with "Only functions and extended stored procedures can be executed from within a function."
Here is the code of function with latest modifications to sp_ procedures. Note: This is REALY out-of-context procedures since it is part of 18 procedures which together creates rough production plan.
How to make this function work?
CREATE function [dbo].[plan_narudzbe] ( @koja_narudzba int, @tip int)
SELECT @NARUDZBA_PLAN_FINI_PLAN = VRIJEDNOST FROM PARAMETRI WHERE NAZIV='NARUDZBA_PLAN_FINI_PLAN'
set @NARUDZBA_PLAN_FINI_PLAN=COALESCE(@NARUDZBA_PLAN_FINI_PLAN,0); if ((@TIP=1) AND (@KOJA_NARUDZBA IS NULL)) return; set @STR= ' SELECT Q.ID,Q.ID_ARTIKL, COALESCE(Q.POTVRDA_KOLICINA,Q.KOLICINA,0) AS KOLICINA, COALESCE(Q.POTVRDA_TERMIN_ISPORUKE,Q.TERMIN_ISPORUKE) AS TERMIN, N.STATUS , SUM(RN.KOLICINA_NALOGA) AS U_PROIZVODNJI FROM NARUDZBA_STAV Q LEFT JOIN RADNI_NALOG RN ON (RN.ID_NARUDZBA_STAV=Q.ID) LEFT JOIN NARUDZBA N ON (Q.ID_NARUDZBA=N.ID) WHERE Q.STATUS NOT IN (2,5,8,9) '; if (@KOJA_NARUDZBA IS NOT NULL) set @STR=@STR+' AND Q.ID='+cast(@KOJA_NARUDZBA as varchar)+' '; set @STR=@STR+' GROUP BY Q.ID,Q.ID_ARTIKL, COALESCE(Q.POTVRDA_KOLICINA,Q.KOLICINA,0), COALESCE(Q.POTVRDA_TERMIN_ISPORUKE,Q.TERMIN_ISPORUKE), N.STATUS ';
-- Create a dynamc read-only cursor
DECLARE @cursor INT EXEC sp_cursoropen @cursor OUTPUT, @STR, 2, 8193
-- Name the cursor EXEC sp_cursoroption @cursor, 2, 'narudzba_stav'
while (1=1) begin fetch next from narudzba_stav INTO @ID_NARUDZBA_STAV, @ID_ARTIKL, @KOLICINA, @TERMIN_NARUDZBE, @STATUS_NARUDZBE, @U_PROIZVODNJI if (@@fetch_status<>0) break;
set @KOLICINA=@KOLICINA-COALESCE(@U_PROIZVODNJI,0); if (@STATUS_NARUDZBE=12) BEGIN if (@NARUDZBA_PLAN_FINI_PLAN=1) BEGIN set @RASPISANI_PLAN=NULL; SELECT @RASPISANI_PLAN = SUM(KOLICINA) FROM NARUDZBA_STAV_PLAN WHERE ID_NARUDZBA_STAV_PLAN=@ID_NARUDZBA_STAV set @KOLICINA=@KOLICINA-COALESCE(@RASPISANI_PLAN,0); END ELSE set @KOLICINA=0; END if (@KOLICINA>0) BEGIN set @ID_RADNI_PLAN=NULL; SELECT TOP 1 @ID_RADNI_PLAN = ID FROM RADNI_PLAN WHERE ID_ARTIKL=@ID_ARTIKL ORDER BY AKTIVAN_PLAN DESC,ID DESC
insert @ReturnTable values ( @ID_NARUDZBA_STAV, @ID_ARTIKL, @KOLICINA, @ID_RADNI_PLAN, @TERMIN_NARUDZBE) END END -- Close the cursor EXEC sp_cursorclose @cursor
I wrote the following script. Its gets list of tables left joint to compare data between 2 table and insert the difference. My problem is its taking for ever to Run.
FETCH NEXT FROM TableCursor INTO @TableName WHILE @@FETCH_STATUS = 0 BEGIN
DECLARE @Line VARCHAR(1000)
SET @Line = '' SET @ID = ''
SELECT top 1 @ID = @ID + QUOTENAME(c.Column_Name) FROM INFORMATION_SCHEMA.TABLES T JOIN INFORMATION_SCHEMA.COLUMNS C ON t.Table_Name = c.Table_Name WHERE t.Table_Name = @TableName
SELECT @Line = @Line + 'b.'+ QUOTENAME(c.Column_Name) + ' , ' FROM INFORMATION_SCHEMA.TABLES T JOIN INFORMATION_SCHEMA.COLUMNS C ON t.Table_Name = c.Table_Name WHERE t.Table_Name = @TableName
On this site:http://www.sommarskog.se/dynamic_sql.htmlI have found an example how to use cursor with dynamic SQL:DECLARE @my_cur CURSOREXEC sp_executesqlN'SET @my_cur = CURSOR FOR SELECT name FROM dbo.sysobjects; OPEN@my_cur',N'@my_cur cursor OUTPUT', @my_cur OUTPUTFETCH NEXT FROM @my_curBut when I tried to do this:IF (@Naziv <> '')SET @sql_where = @sql_where + N' AND Naziv LIKE ' + @NazivIF (@Funk <> '')SET @sql_where = @sql_where + N' AND Funkcija LIKE ' + @FunkIF (@Mj <> '')SET @sql_where = @sql_where + N' AND NazivMjesta LIKE ' + @MjIF (@Drz <> '')SET @sql_where = @sql_where + N' AND (drzava1 LIKE ' + @Drz +' OR drzava2 like ' + @Drz + ' OR drzava3 LIKE ' + @Drz + ')'DECLARE @CursSearch CURSORSET @sql = N'SET @CursSearch = CURSOR FORSELECT CvorID, NadCvorID,IzvorisniCvorID, Naziv, TipCvora,NasljednaLinija, Funkcija, NazivMjesta,drzava1, drzava2, drzava3FROM dbo.PretrazivanjeWHERE NasljednaLinija LIKE @NasljednaLinija'+ @sql_where + N'; OPEN @CursSearch'EXEC sp_executesql @sql, N'@CursSearch CURSOR OUTPUT',@CursSearch OUTPUT....by fetching cursor i got this message:The variable '@CursSearch' does not currently have a cursor allocated to it.Can anybody tell me what i did wrong?
i want to store the output in out variable .Which gives multiple values.
create procedure usp_test (@AccountID INT) as begin DECLARE @getAccountID CURSOR SET @getAccountID = CURSOR FOR SELECT Account_ID FROM Accounts OPEN @getAccountID FETCH NEXT FROM @getAccountID INTO @AccountID WHILE @@FETCH_STATUS = 0 BEGIN PRINT @AccountID FETCH NEXT FROM @getAccountID INTO @AccountID END CLOSE @getAccountID DEALLOCATE @getAccountID end
i get nearly ten rows in the print statement how can i assign the output to a out variable where i get all ten rows.
Hi, I have compact sql databases which will be local on multiple users devices. Due to space constraints, for one of the tables i have had to use auto incrementing integer which works fine for the local database but i would like to merge all of the users databases into a global database. The table format can be seen below:
Code SnippetCREATE TABLE Players ( ID UNIQUEIDENTIFIER NOT NULL PRIMARY KEY, FirstName NVARCHAR(32), LastName NVARCHAR(32) );
The Players table will merge fine as GUIDs are used. However, how will the sync capabilities of compact SQL handle the sessions table? When it pushes the local data to the remote database will it change the Sessions.ID column to a unique field (as no doubt lots of people will have 1, 2, 3 in their local databases and the global database must have a unique ID), and then transfer this changed ID back to the local database? Furthermore, if it changes the Sessions.ID column during the merge it will also need to update the SessionDetail.SessionID foreign key to maintain referential integrity, is this also handled?
So my question is, how much of this sync and data merge is automated and are there any good examples or pointers for my scenario? I cannot reasonably use a GUID for Session.ID as there will be lots of SessionDetail entries and the size would be far too much.
Hi All,I tried to get a global variable in my task scritp by using "Dts.Variables("myVar").Value", every time I've got an errorThe element cannot be found in a collection. This error happens when you try to retrieve an element from a collection on a container during execution of the package and the element is not there. I've seen some examples online to get global varaibles in task script and all of them display the same code Any idea Franck
How to create my own global variable and set its value. In another word, i want to set the value of a variable in one sp and want another sp to see its value.
Is there a way to declare a global variable that can be used in seperate stored procedures?
I have a statistics table that tracks the inserts and updates for several stored procedures.
I need to have the procedure_A run and insert a count of inserted and updated rows.
Procedure_B needs to identify the row inserted by procedure_A and update the columns with a count of how many it inserted and updated.
Procedure_C needs to do the same as procedure_b.
I want to pass a global variable with the id of the row inserted by procedure_A to the rest of the procedures so that they will know which row to update. How do I do this? Can I?
Hi all, I have a user using this tool, which creates a temporrary storeproc in tempdb. when I don't give him permission on temp_db, it errors out and says you should create a system variable to point to a different database to create this sp.
Can anyone kindly explain to me how could this be done? I appreciate any comment on this thread.
I want to know that how can i declare a global variable in database, assign some value to it, then using it in multiple triggers and procedure then deallocating that.