How To Update When Dynamic Select SQL By Using SQLDatasouce In .net 2.0?

Apr 5, 2007

In Dot net 2.0 we change using SQLDataSource to Conect with SQLDB.

Now for My case ,the Select SQL is dynamic when differnece user and parameters to the page, So if I want to Update the data input by user,then I must give Update/insert/delelte SQL to SQLDatasource's InsertCommand /UpdateCommand/DeleteCommand . 

How to Generate the Insert/update/delete command for the SQLDataSource ? as in dot net 1.1 can use SQLCommandBuilder to generate it,but SQLCommandBuilder  just support DataAdeptor not for SQLDataSource, Could any body know how to do it when the SelectCommand is dynamic and need to update data back to DB after edit?

 thanks a lot.

View 4 Replies


ADVERTISEMENT

How To Use Update Command At Sqldatasouce

Sep 24, 2007

 hello all..,i have problem in update sqldatasource,  my code like that:me.sqldatasource.updateparameter(index).defaultvalue=valueme.sqldatasource.update()it can not update data, why?but if i use insert or delete like:me.sqldatasource.insertparameter(index).defaultvalue=valueme.sqldatasource.insert()me.sqldatasource.deleteparameter(index).defaultvalue=valueme.sqldatasource.delete()it can work for insert and delete data...can anyone give me update command code in sqldatasouce? plsss...thx...  

View 11 Replies View Related

Dynamic Select/Update Statement Possible?

Dec 3, 2004

Would it be possible to retrieve a "dynamically" named field from a table by using an input parameter?

For example, if a table has fields named Semester1, Semester2, Semester3, Semester4, and I was lazy and only wanted to create one stored procedure for all semesters could I do the following...

ALTER PROCEDURE u_sp_x
@semester int
AS
Select Semester@semester
From ThisTable

Just curious.

Thanks,
Steve Hanzelman

View 6 Replies View Related

SQL Server 2012 :: Create Dynamic Update Statement Based On Return Values In Select Statement

Jan 9, 2015

Ok I have a query "SELECT ColumnNames FROM tbl1" let's say the values returned are "age,sex,race".

Now I want to be able to create an "update" statement like "UPATE tbl2 SET Col2 = age + sex + race" dynamically and execute this UPDATE statement. So, if the next select statement returns "age, sex, race, gender" then the script should create "UPDATE tbl2 SET Col2 = age + sex + race + gender" and execute it.

View 4 Replies View Related

SqlDataSouce.SelectCommand

Feb 3, 2006

How do you programmatically change the SQL select statement for the SelectCommand in a SqlDataSource?For instance, if I had two buttons on a page, and for one button, I'd like it to change the select command to be "SELECT * FROM authors WHERE au_id > 100". Then for the second button, I'd like it to show "SELECT * FROM authors WHERE au_lname like S%".Anybody know the code to do this? I was trying to type the code, but the intellisense didn't give me any options to pick from after I typed SqlDataSouce1.SelectCommand.

View 3 Replies View Related

Looping Through SQLDataSouce In A Function

Feb 17, 2006

Hi All,
Thanks for looking at the post. Here is what I am trying to do:
Lets say I have dragged and dropped a new SqlDataSource onto the page and called it SQLDataSource2
Now, in a function that happens afterload:
Protected Sub Partners_afterLoad(ByVal sender As Object, ByVal e As System.EventArgs)
I want to be able to loop through that SQLDataSource2, and pull a value to compare.
In classic ASP it would be something like:
'Move to the first recordSQLDatasource.MoveFirst'Loop through RecordsetWhile Not SQLDataSource2.Eof'Do compare of the Field MyValueIf SQLDataSource2("MyValue")=27 Then Reponse.Write "Hit on # 27"'Move to Next RecordSQLDatasource.MoveNext'End the loopWend
My questions are as follows:
1) Do I need to define the Datasource in the function, or can I use the one that VWD2005 helped me to define.
2) How can I loop throught that Datasource (Recordset) in a function.
Any and all help appreciated--Code examples will make me your best friend.
 
 

View 7 Replies View Related

How To Access Underlaying DataView Of SQLDataSouce In It's Selected Event

Jun 30, 2006

I need access to the underlying DataView associated with a declaratively defined SQLDataSource. Ideally, I need this access in the SQLDataSource's Selected event. I know that I can use the SQLDataSouce.Select() method to return the underlying DataView object. But, there is a GridView control bound to the datasource so I don't want to explicity call Select() since it will end up being called again implicity by the gridview itself. I have seen that this can be done with an ObjectDataSouce as follows:
void odsDataSouce_Selected(object sender, ObjectDataSourceStatusEventArgs e) {  DataView oDV = (DataView)e.ReturnValue;}
Is there any way to accomplish the same thing with a SQLDataSouce?  It seems hard to believe that the query results are not exposed to the Selected event.
Thanks!
 
 

View 4 Replies View Related

Modified Sqldatasource.filterExpression While Sqldatasouce.selecting Event

Apr 25, 2008

I facing a problem when i want to modified the sqldatasource.filterExpression while trigger sqldatasource.selecting event.   1 Protected Sub SqlDsProduct_Selecting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.SqlDataSourceSelectingEventArgs)
2 Dim SqlDsProduct As SqlDataSource = CType(CompleteGridView1.DetailRows(0).FindControl("SqlDsProduct"), SqlDataSource)
3 SqlDsProduct.FilterExpression = Session("filter") ' filter i add up after user press search button
4 End subActually i'm using the CompleteGridview, which i downloaded from the web. the "SqlDsProduct" i reffering to is inside the CompleteGridView1. I'm using complet grid view because i want the hierarchy look for the gridview. So please help me how i gonna change the filter expression of the 2nd sqldatasource inside detailsTemplate of the completeGridview. Thank you. best regardvince
 

View 6 Replies View Related

Dynamic Update

Jul 30, 2007







i have a table with the following values

iden nam status
----------- -------- --------------------
1 pp NULL
1 kk NULL
2 rr NULL
2 nn NULL
2 jj NULL
3 hh NULL


now i want to update the status cloumn in this table in such a way that the status colum = 'Status is' + iden + nam for all distinct values of iden from the table

how can we do this without using a cursor?

View 2 Replies View Related

Dynamic Update System

Jan 12, 2007

Hello folks!I'm have some trouble with a dynamic update system! What I want to do: 1. I want to send in the code behind from any .aspx file values and parameters to a .vb class2. Code (code behind in .aspx file):1            gridupdate.updategrid("tblFeedbackA", e.CommandArgument, "locked=@locked", "@locked", "int", "0") 'Call de .vb class2    getgridfeedback()  
3. Code (code in .vb class)1 Public Shared Function updategrid(ByVal tblnaam As String, ByVal x As Integer, ByVal sql As String, ByVal parameters As String, ByVal sqltype As String, ByVal waarden As String 'translation: values)
2 Dim dynstr As String()
3 Dim dynstr2 As String()
4 Dim re As New Regex(",")
5 dynstr = re.Split(parameters)
6 Dim i As Integer
7 dynstr2 = re.Split(sqltype)
8 Dim dynstr3 As String()
9 dynstr3 = re.Split(waarden)
10
11 Dim sqlconn As New SqlConnection(ConfigurationManager.ConnectionStrings("DataBase").ConnectionString)
12 Dim sql2 As String = "UPDATE " & HttpContext.Current.Session("prefix").ToString & tblnaam & " set " & sql & " where id=" & x
13 Dim sqlcmd As New SqlCommand(sql2, sqlconn)
14 sqlconn.Open()
15
16 For i = 0 To dynstr.Length - 1
17 sqlcmd.Parameters.Add(dynstr(i), CType("sqldbtype." & dynstr2(i), System.Data.SqlDbType))
18 sqlcmd.Parameters(dynstr(i)).Value = dynstr3(i)
19 Next
20 sqlcmd.ExecuteNonQuery()
21 sqlconn.Close()
22 Return Nothing
23 End FunctionAll I want to do is to add the sqlparameters dynamically, but I don't find a way to do this :).Can you help me out?Thanks! 

View 1 Replies View Related

Dynamic Update Linked Server

Nov 28, 2014

How to write this query so that I can pass a variable (from a cursor) for the were ORDER_ID =.

UPDATE OPENQUERY ([DISPATCHER_LIVE], 'select * from DCSDBA.ORDER_HEADER where ORDER_ID = ''405119-RM18''')
SET CONSIGNMENT = 'UNROUTED'

View 2 Replies View Related

Best Way To Create Dynamic Update Statement

Jul 23, 2005

In general, What is the best approach in creating a dynamic updatestored procedure, that can handle recieving varying input paramters andupdate the approporiate columns.

View 6 Replies View Related

Dynamic If Update() In Trigger - Urgent!

Jul 23, 2005

Hi AllI have a question about generating dynmamicly If Update() statement in atrigger..in My db, there is a table that holds some column names of an another table.for example;Columns Table-A: Col1, Col2, Col3, Col4,Col5Table-B: Col2, Col5 (The selected columns of Table A)Then, in the Trigger of Table-A I use;Select name from syscolumns where id=object_id('Table-A')fetch next from TableA_Cursor into @strColNamethen, I used a statement like this..if UPDATE(' + @strColName + ')But it gives "incorrect syntax" error..How can I write this line?Thanks alot in advance...--Message posted via http://www.sqlmonster.com

View 1 Replies View Related

Insert/Update With Dynamic Database Name

Jan 25, 2006

HiMy problem is as follows:I need to transmit data between two databases on the same server, but Ihave to use dynamic database names (they must be configurable). Forexample I need to achive sth like that:insert into [database1].[dbo].[table1](select columns from [table2])when database1 is not known at implementation stage.I know I can use EXEC @t_sql_code, but I wonder if there is any otherway? (OPENROWSET doesn't seem to suit my needs)Thanks in advanceAmfi

View 1 Replies View Related

Table Update With Dynamic Data

Apr 23, 2008



OK, I'm trying to add some audit type information to a set of tables in my database. This involves adding 2 columns and sticking some data into those two columns. The columns themselves are added successfully, but I'm having troubles sticking any data into them - I'm getting a lot of errors. What I want to do is put a single character code in one column, and a datetime in the second. Here's the SQL I'm trying...




Code Snippet
SELECT @SQL = N'UPDATE ' + QUOTENAME(@TableName) + ' ' +
N' SET TRANSACTION_CODE = ''' + @TxCode +
N''', EFFECTIVE_DATE = ''' + @TxDateTime + ''';'
SELECT @Params = N'@TxCode varchar(1), @TxDateTime datetime'
EXEC sp_executesql @SQL, @Params, @TxCode, @TxDateTime





But this errors out with:

Msg 241, Level 16, State 1, Line 64

Conversion failed when converting datetime from character string.

I tried changing the datetime column to varchar, and CONVERT(varchar(30),@TxDateTime). That gets rid of the above error, but replaces it with the following (twice, I might add - one for each column?):

Msg 213, Level 16, State 1, Line 1

Insert Error: Column name or number of supplied values does not match table definition.

Any help is appreciated - let me know if you need more info.

View 14 Replies View Related

Spooky Semi-dynamic Sql Update Statement

Nov 9, 2006

Hi,
I rewrote my working Sql statement to prevent Sql Injections. I copied some code I used in another project but this time I can't get it to work, possibly because it's an update statement and not an Insert one, which I used before.
Sorry for the boring question, but does anyone have a clue what's wrong with the syntax?
Here's the original code (I changed the parameter names for clarity and security):
    Dim conn As SqlConnection = New SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings("MyConnectionString").ConnectionString)    Dim strSQL As String = "Update MyTable Set " & typ & num & " = '" & pname & "' WHERE personID = " & fid    Dim cmd As SqlCommand = New SqlCommand(strSQL, conn)
Here's the code from codebehind:
    Dim conn As SqlConnection = New SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings("MyConnectionString").ConnectionString)    Dim strSQL As String = "Update MyTable Set (" & typ & num & ") Values (@" & typ & num & ") WHERE personID = " & fid    Dim cmd As New SqlCommand(strSQL, conn)    With cmd.Parameters       .Add(New SqlParameter("@" & typ & num, pname))    End With    TestLabel.Text = strSQL & "        " & pname    cmd.Connection.Open()    cmd.ExecuteNonQuery()    cmd.Connection.Close()   
Here's my test message; first the sql, then the new string to be inserted:
Update MyTable Set (picturename) Values (@pname) WHERE personID = 2       2_adin.jpg  
Here's my error code:
Line 1: Incorrect syntax near '('. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Data.SqlClient.SqlException: Line 1: Incorrect syntax near '('.
Source Error:
Line 489:            TestLabel.Text = strSQL & "  " & pnameLine 490:            cmd.Connection.Open()Line 491:            cmd.ExecuteNonQuery()Line 492:            cmd.Connection.Close()Line 493:        End If 
I could understand it if I'd get an error in VWD Express for using dynamic variables, but they work correctly in the text message so I'm clueless. Any help is deeply appreciated!
Pettrer (VB, Sql Server 2000)
 
 

View 2 Replies View Related

Cannot Update 1 Of 2 Tables - Dynamic SQL Generation Is Not Supported

Jan 14, 2008

Hi, I'm having a problem with my code,I am doing the following - retrieving a field from a table, which is linked to another table, i'm only updating one of the fields in one of the two tables...
Code: ( text )

View 1 Replies View Related

T-SQL (SS2K8) :: Generate Dynamic Update Statement

Aug 14, 2014

I'm trying to generate an update statement based off select statement results. A very basic example,

SELECT ListID FROM DListing WHERE Status = 2Results return 3 rows.
1234
2345
3456

How can I take those results and turn them into WHERE criteria for UPDATE statement?

Generated UPDATE statement should look like this.

UPDATE DListing SET Status = 1 WHERE ListID IN (1234,2345,3456)

I have started by creating a temp table to hold my SELECT results, but I don't know how to get those results into format for IN condition. Right now I get 3 UPDATE statements with 1 ListID in each IN condition.

CREATE TABLE #TempStatusUpdate(ListID INT)
INSERT INTO #TempStatusUpdate
SELECT ListID FROM DListing WHERE Status = 2
SELECT 'UPDATE DListing SET Status = 1 WHERE ListID IN (' + CONVERT(VARCHAR(30),ListID) + ') AND Status = 2'
DROP TABLE #TempStatusUpdate

View 6 Replies View Related

Need Dynamic SQL Select Turotrial

Jun 5, 2007

Need a tutorial on how to use ASP.net to dynamically build a SQL2000 compatible SELECT statement for a multiple keyword search. I need a search that will find any combination of one or more keywords in the Keyword string in any order.
Thank you
 

View 8 Replies View Related

' In A Dynamic Select String?

Apr 12, 2005

I'm building a select string on the fly based on criteria selected by the user.  The user is given a data grid with Names and Check Boxes, where they can select multiple names and then either print those selections, or download them to excel.  Everything is working fine, except when the Name has an ' in it.  For example O'Kelly or St. John's.  I know I can take all the 's out of the database, but I'd rather keep the data authentic.  Is there a way to manipulate a select string built on the fly accounting for an embedded '?
For example, I build Select * from table where Name IN ('Smith', 'Jones', 'Jordan', 'Bird', 'O'Kelly').... the ' in O'Kelly ends my string and my sql statement blows up.
Any ideas?
Sample Code:<code>         For Each SelectedIndex In rsc.SelectedIndexes                Counter=Counter + 1                dgAssociates.SelectedIndex = SelectedIndex                If Counter = 1 then                    SelectString = "Select * from Associate_Table where AssociateID IN ('" & dgAssociates.SelectedItem.Cells(16).Text() & "'"                Else                    SelectString &= ",'" & dgAssociates.SelectedItem.Cells(16).Text() & "'"                End If            Next            If Counter > 0 then                SelectString &= ")"            End If</code>

View 2 Replies View Related

Dynamic Select For CURSOR

May 14, 2008

Hi all

I am trying to do dynamic Select for Cursor. The dynamic would be like this:
IF CONDITION1 IS TRUE:
SELECT CustomerTenderID, CustomerSiteID, ContractPeriod, SupplierID
FROM dbo.tnd_TenderSiteRateConsumptionView
WHERE CustomerTenderID = @CustomerTenderID
IF CONDITION2 IS TRUE:
SELECT CustomerTenderID, CustomerSiteID, ContractPeriod, SupplierID
FROM dbo.tnd_TenderSiteRateConsumptionView
WHERE CustomerTenderID = @CustomerTenderID AND
CustomerSiteID = @CustomerSiteID

etc etc

Here's the cursor


DECLARE RateList CURSOR FOR
SELECT CustomerTenderID, CustomerSiteID, ContractPeriod, SupplierID
FROM dbo.tnd_TenderSiteRateConsumptionView
WHERE (BASED ON CONDITION)
ORDER BY CustomerTenderID,
CustomerSiteID,
SupplierID,
ContractPeriod

OPEN RateList
FETCH NEXT FROM RateList
INTO@CustomerTenderID, @ReturnedCustomerSiteID, @ReturnedContractPeriod, @ReturnedSupplierID
WHILE @@FETCH_STATUS = 0
BEGIN
SET @rowNum = @rowNum + 1

-- DO SOME FUNKY STUFF


FETCH NEXT
FROM RateList
INTO@CustomerTenderID, @ReturnedCustomerSiteID, @ReturnedContractPeriod, @ReturnedSupplierID

View 4 Replies View Related

Select @@RowCount In Dynamic Sql

Feb 23, 2008

hi, how to retrieve row count from an insert statement in dynamic sql?


CREATE PROCEDURE [dbo].[procTest]
AS
BEGIN
SET NOCOUNT ON;

DECLARE @nsql NVARCHAR(MAX)
DECLARE @i INT
SET @nsql = 'select * into tbl_user_test from tbl_user;
select @i = @@rowcount;'
exec sp_executesql @nsql;
END


The code doesn't work..

declare @i int;
Exec procTest, N'@i int output',@i=@i output
select @i;

View 3 Replies View Related

Dynamic SELECT Query

May 21, 2008

I need to implement a "dynamic" select query, in which I want that the type and the number of columns are variable/changeable. For example using the parameters of a stored procedures. I would have a client code (written in VB .NET) in which I would choose the columns that I want to display in a DataGridView.


How should I modify the SELECT line or the SP in general to solve the problem??


The code I need to modify is this:



Code Snippet
CREATE PROCEDURE uspSelect1
@iDataInit datetime = '01 gen 1753',
@iDataEnd datetime = '31 dic 9999',
@iArticle nvarchar(50) = N'%',
@iMachineNum smallint,
@iTypeMaterial nvarchar(50) = N'%',
@iNominalCount float,
@iOperator nvarchar(50) = N'%',
@iCustomer varchar(50) = N'%',
@iComments nvarchar(1000) = N'%',
@iLanguage nvarchar(50) = N'%'
AS
SELECT i.IDsample, i.Date, i.Article, i.MachineNum, i.TypeMaterial, i.NominalCount, i.Operator, i.Customer, i.Comments, i.Language, r.Um, r.CVm
FROM Identification i JOIN Reports r
ON (i.IDsample = r.IDsample)
WHERE i.Date BETWEEN @iDataInit AND @iDataEnd
AND i.Article LIKE @iArticle
AND i.MachineNum = ISNULL(@iMachineNum, i.MachineNum)
AND i.TypeMaterial LIKE @iTypeMaterial
AND i.NominalCount = ISNULL(@iNominalCount, i.NominalCount)
AND i.Operator LIKE @iOperator
AND i.Customer LIKE @iCustomer
AND i.Comments LIKE @iComments
AND i.Language LIKE @iLanguage
ORDER BY i.IDsample


Thank you.
Gabriele

View 8 Replies View Related

Select Dynamic Issue

Dec 4, 2007



Hi,

I have a table with 20 column 10 with the name in1,in2,in3... and 10 more with the name out1,out2,out3...
what i'm trying to do is a loop that will substract all column like this

sum = out1-in1
sum = sum + (out2-in2)
etc etc..

what is your suggestion for the best way doing that.

thanks.

View 2 Replies View Related

Select Into Using Dynamic Queries

May 5, 2008

I need to create a temporary table using dynamic queries and then i have to use the temporary table for data manipulatuion.

Can someone help me out on this.

EG
sp_executesql N'Select top 1 * into #tmp from table1'
select * from #tmp

View 5 Replies View Related

Dynamic SELECT Command In SqlDataSource

Jul 20, 2007

I have a GridView (that uses SqlDataSource1) and a Dropdownlist.  Depending upon the value selected on the DropDownList I need to select different stored procedures for the gridview.  The problem is that I can do it without taking SqlDataSource1 by using DataSet or DataTable.  But, I need to Use SQLDataSource1 for easy way of Header SORTING.  So, is there any way to change the SQLDatasource1.SELECT Command dynamically. So that, I can use different queries for the Single DataGrid. I have attached the sample code of the SqlDataSource1 I'm using.  I need to change the Command i.e. SelectCommand="usp_reports_shortages" to "usp_reports_shortagesbyID" and "usp_reports_shortagesbyDate"     depending on the value selected in the dropdownlist.  So, is there any way to do this????<asp:SqlDataSource ID="SqlDataSource1"
runat="server"
ConnectionString="<%$
ConnectionStrings:TESTDrivercommunication %>"


    SelectCommand="usp_reports_shortages" SelectCommandType="StoredProcedure">


    <SelectParameters>


        <asp:ControlParameter ControlID="lblDriver" Name="date1" PropertyName="Text" Type="DateTime" />


        <asp:ControlParameter ControlID="lblTODate" Name="date2" PropertyName="Text" Type="DateTime" />


        <asp:ControlParameter ControlID="DDlDriver" Name="driver" PropertyName="SelectedValue"


            Type="Int32" />


        <asp:SessionParameter Name="week" SessionField="s_week" Type="DateTime" />


    </SelectParameters>


</asp:SqlDataSource>

View 1 Replies View Related

Dynamic SqlDataSource Select Command?

Apr 25, 2008

I am trying to implement an "advanced search" feature on my ASP.NET 2.0 web form.  I have a GridView control and a SqlDataSource.  The SqlDataSource control successfully retrieves data when the SelectCommand attribute is set in the aspx page.  I need to make it so when a user clicks on a button, it can take a value from a text box and use it in the WHERE clause.  I have tried setting the SelectCommand programmatically and then DataBinding but it never accepts the new SelectCommand. What can I do to fix this?

View 5 Replies View Related

Convert Variable Into Dynamic Select

Jul 23, 2005

I am trying to assign @sql variable to @total, where @sql is a sqlstatement stored on the database, however what I am getting is itsstring value and not its calcuation. Could anybody help?DECLARE my_cursor CURSOR FORSELECT sqlstatement from Sn_SalesReportdeclare @sql varchar(255), @total varchar(20)OPEN my_cursorFETCH NEXT FROM my_cursor INTO @sql-- Check @@FETCH_STATUS to see if there are any more rows to fetch.WHILE @@FETCH_STATUS = 0BEGINSET @total = (@sql)print @total-- This is executed as long as the previous fetch succeeds.FETCH NEXT FROM my_cursorINTO @sqlENDCLOSE my_cursorDEALLOCATE my_cursorI tried this SET @total = EXEC (@sql), but no successRod

View 9 Replies View Related

Dynamic Column Bind (Select * From..)

Jul 9, 2007

I'm looking for a way to use SSRS to display the contents of a returned dataset with 1-n columns. The number of columns is unknown at design time and the datasetview is using a stored procedure with 1 parameter to return the data. Does any one know if RDL supports wildcard(*) characters for field names or if there is another method.



I have this working via a web based custom aspx page but it would be VERY helpful to utilize all the document conversion features the SSRS reports provide via the web.



Thanks for any help.

IT Publisher

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

Wrapping A Dynamic Sql Call In A Select

Mar 13, 2008

I'm expecting to revamp some stored procs so that their selects are executed on a dynamic string that always returns the same columns but varies the sources.

I'm concerned that the bread and butter of products like RS and SSIS is the ability to predict what columns, and what column types to expect from a query, but that introducing dynamic sql will complicate using them.

I'm motivated not to use temp tables or table vars if possible. I'm also somewhat motivated to learn of a solution that works equally well in 2000 and 2005.

I've tried wrapping dynamic calls in a select as shown below but to no avail...


After€¦

declare @sqlString nvarchar(4000)
set @sqlString = 'select * from [' + @dbName + '].[dbo].[activity]'

I€™ve already tried things like€¦.
select a.* from exec sp_executesql @sqlString a

and

select * from exec (@sqlString)

View 8 Replies View Related

Dynamic Column Names In Select Statement

Oct 13, 2001

I have a quick question on SQL Server. Lets say I have table Order which has column names OrderId, CustomerName, OrderDate and NumberofItems. To select the OrderID values from the table I say
Select OrderId from Order.
But in the select if I want the column name to be variable how do I do it. I tried the following code through a stored procedure.

declare @order_id nvarchar(10)
select @order_id = 'OrderID'
SELECT @order_id from Order.

The code above gave me the string "OrderID" as many times as there were rows in the table but I could never get the actuall values in the OrderId column. Can you please send me some ideas or code where I can get values from the column names and at the same time change the column name dynamically.

View 1 Replies View Related

Dynamic CREATE TABLE Or SELECT INTO Statement

Jul 27, 2004

In SQL Server you can do a SELECT INTO to create a new table, much like CREAT TABLE AS in Oracle. I'm putting together a dynamic script that will create a table with the number of columns being the dynamic part of my script. Got any suggestions that come to mind?

Example:

I need to count the number of weeks between two dates, my columns in the table need to be at least one for every week returned in my query.

I'm thinking of getting a count of the number of weeks then building my column string comma separated then do my CREATE TABLE statement rather then the SELECT INTO... But I'm not sure I'll be able to do that using a variable that holds the string of column names. I'm guess the only way I can do this is via either VBScript or VB rather then from within the database.

BTW - this would be a stored procedure...

Any suggestions would be greatly appreciated.

View 1 Replies View Related







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