Hi Folx, I am new to SQL Server. I am rolling summed values from table profile to two columns in table txn. When the value for one (not necessarily both...) column is null, can that value be translated to zero? Or must I write a procedure or use a cursor? Versions: Microsoft SQL Server Integration Services Designer Version 9.00.1399.00
Microsoft SQL Server Management Studio 9.00.1399.00
For example, when version_count for a particular transaction_id is null in the profile table but profile_count has summable integers, how do I update the version_count to zero in the same pass that I update the profile_count?
update txn set version_count = ( select sum(a.version_count) from profile a where a.transaction_id=txn.transaction_id and a.extraction_date=txn.extraction_date and txn.version_count is null ), profile_count = ( select count(*) from profile a where a.transaction_id=txn.transaction_id and a.extraction_date=txn.extraction_date and txn.profile_count is null )
Hi all,I have a stored procdure which does a select and returns the recordsdirectly -i.e. Not in output parameters e.g:CREATE PROCEDURE up_SelectRecs(@ProductName nvarchar(30)) ASSELECT *FROM MyTableWHERE [Name]=@ProductNameIn another stored procedure I need to do the following:SELECT COUNT(*)FROM MyTableWHERE [Name]=@ProductNameAs the select queries are actually a lot more complex that this, I'drather not duplicate the select code in 2 sp's to save the maintenanceeffort - I'm looking for a way to execute the first procedure from thesecond and just count the records returned - something like:SELECT Count(*)FROM EXEC up_SelectRecs @ProductNameAny way to achieve this?Thanks all--James
Is it possible to get the result from an EXEC(@sqlcommand) statement into a variable?
As part of a SQL loop, it is necessary for me to run an EXEC() command to process an SQL statement. I have succesfully implemented this, but have been unable to get the results from the EXEC() statement into a variable to allow this data to be inserted into a table. Is this possible?
For Example (I know this doesn't work, but it is effectively what I am trying to achieve):
select @result = EXEC(@sqlcommand)
I could then use the @result variable in an insert statement to update a table with the results from the EXEC command.
I am building a SQL statement that returns a number.when I execute the Built SQL statment EXEC(@Build). What I need to donow is take that number that comes back and store it in anothervariable so I can do some conditional logic. Any ideas? See SQL below.Something like @Count=Exec(@Build) which I know doesnt work.Thanks,PhilDECLARE @PullDate varchar(12)SET @PullDate=''+CAST(DATEPART(mm,getdate()-31) AS varchar(2))+'/'+CAST(DATEPART(dd,getdate()-31)AS varchar(2))+'/'+CAST(DATEPART(yyyy,getdate()-31) AS varchar(4))+''PRINT(@PullDate)DECLARE @COUNTER BIGINTDECLARE @SELECT VARCHAR(500)DECLARE @SELECT2 VARCHAR(1000)DECLARE @BUILD VARCHAR(5000)SET @SELECT='SELECT COUNTER FROMOPENQUERY(PROD,'SET @SELECT2='''SELECTCOUNT(WMB.COLLECTOR_RESULTS.ACCT_NUM) AS COUNTERFROMCOLLECTOR_RESULTS,WHEREWMB.COLLECTOR_RESULTS.ACTIVITY_DATE =to_date('''''+@PullDate+''''',''''mm/dd/yyyy'''')AND WMB.COLLECT_ACCOUNT.END_DATE ) =to_date(''''12/31/9999'''',''''mm/dd/yyyy'''')AND WMB.COLLECT_ACCT_SYS_DATA.END_DATE =to_date('''''+@PullDate+''''',''''mm/dd/yyyy''''))GROUP BYWMB.COLLECTOR_RESULTS.ACTIVITY_DATE '')'SET @BUILD=@SELECT+@SELECT2PRINT(@BUILD)EXEC(@BUILD)--THIS IS WHERE IM UNSURE I NEED THE COUNT RETURNED FROM @BUILD STOREDINTO @COUNTER so I can do a conditional statement.)if @COUNTER>=1beginprint('yes')end
Here is the scenario, I have 2 stored procedures, SP1 and SP2
SP1 has the following code:
declare @tmp as varchar(300) set @tmp = 'SELECT * FROM OPENROWSET ( ''SQLOLEDB'', ''SERVER=.;Trusted_Connection=yes'', ''SET FMTONLY OFF EXEC ' + db_name() + '..StoredProcedure'' )'
EXEC (@tmp)
SP2 has the following code:
SELECT * FROM SP1 (which won't work because SP1 is a stored procedure. A view, a table valued function, or a temporary table must be used for this)
Views - can't use a view because they don't allow dynamic sql and the db_name() in the OPENROWSET function must be used. Temp Tables - can't use these because it would cause a large hit on system performance due to the frequency SP2 and others like it will be used. Functions - My last resort is to use a table valued function as shown:
FUNCTION MyFunction ( ) RETURNS @retTable ( @Field1 int, @Field2 varchar(50) ) AS BEGIN -- the problem here is that I need to call SP1 and assign it's resulting data into the -- @retTable variable
-- this statement is incorrect, but it's meaning is my goal INSERT @retTableSELECT *FROM SP1
I have a strange problem. I have some code that executes a sql query. If I run the query in SQL server query analyzer, I get a set of data returned for me as expected. This is the query listed on lines 3 and 4. I just manually type it into query analyzer. Yet when I run the same query in my code, the result set is slightly different because it is missing some data. I am confused as to what is going on here. Basically to examine the sql result set returned, I write it out to an XML file. (See line 16). Why the data returned is different, I have no idea. Also writing it out to an XML file is the only way I can look at the data. Otherwise looking at it in the debugger is impossible, with the hundreds of tree nodes returned. If someone is able to help me figure this out, I would appreciate it. 1. public DataSet GetMarketList(string region, string marketRegion)2. {3. string sql = @"SELECT a.RealEstMarket FROM MarketMap a, RegionMap b " + 4."WHERE a.RegionCode = b.RegionCode"; 5. DataSet dsMarketList = new DataSet();6. SqlConnection sqlConn = new SqlConnection(intranetConnStr); 7. SqlCommand cmd = new SqlCommand(sql,sqlConn);8. sqlConn.Open();9. SqlDataAdapter adapter = new SqlDataAdapter(cmd); 10. try11. {12. adapter.Fill(dsMarketList); 13. String bling = adapter.SelectCommand.CommandText;//BRG 14. dsMarketList.DataSetName="RegionMarket"; 15. dsMarketList.Tables[0].TableName = "MarketList"; 16. dsMarketList.WriteXml(Server.MapPath ("myXMLFile.xml" )); // The data written to 17. myXMLFile.xml is not the same data that is returned when I run the query on line 3&4 18. // from the SQL query 19. } 20. catch(Exception e) 21. { 22. // Handle the exception (Code not shown)
Hello everyone, i have the parameter in my stored procedure that i am using as a sqldatasource.
Now in one of the events, i need to assign a value to the parameter. How can i do that? Microsoft is changing the syntax so often, all solutions i found on this forum just don't work anymore, like: SqlDataSource1.SelectParameters["@CompareInteger"].value= "1" OR SqlDataSource1.SelectParameters["@CompareInteger"].DefaultValue= "1"
I guess the SelectParameter - became 'ReadOnly'..But how to assign value to a parameter now?!? Thanks for any help
I use SQL Server 2005 and in a Stored Procedure I want to execute a sql statement and assign the result to a variable. How can I do that?The name of the column I want to retreive the value from is "UserID"Here's my SP so far: ALTER PROCEDURE [dbo].[spUnregisterUser] @UserCode int AS BEGIN SET NOCOUNT ON; declare @uid uniqueidentifier --get userid SELECT @uid=UserID FROM tblUserData WHERE UserCode=@UserCode -- Delete user UPDATE tblUserData SET IsDeleted='True' WHERE UserCode=@UserCode END
I have this query and I tried this but am getting the error for the case statement when I assign the nulls to a 0:
The error is they data types of the result expression of a CASE expression are not compatible.
SELECT 'C' as account, FUND_dim.fund_cde as FUND, case when sum(BRKGRPTT.daily_brkg_fact.accum_unit_cnt) is null then '0' else sum(BRKGRPTT.daily_brkg_fact.accum_unit_cnt) end as Units_Purchased FROMFUND_DIM left outer join BRKGRPTT.daily_brkg_fact on FUND_DIM.FUND_ID_NUM = BRKGRPTT.daily_brkg_fact.FUND_ID_NUM and BRKGRPTT.daily_brkg_fact.SEP_ACCT_ID_NUM <> 1 left outer join SEP_ACCOUNT_DIM on BRKGRPTT.daily_brkg_fact.sep_acct_id_num = SEP_ACCOUNT_DIM.sep_acct_id_num group by BRKGRPTT.sep_account_dim.sep_acct_cde, BRKGRPTT.fund_dim.fund_cde order by FUND_dim.fund_cde
How do I assign XmlDocument results to a variable (so that I can pass it to a sp)?
I know that the following code works....
select * from tblUsers where userId = 1225 for XML raw
It returns "<row UserId="1225" LastName="Evans" FirstName="Stephanie" MiddleInitial=...."), which is what I want. But when I try to assign it, I get an error "Incorrect syntax near 'XML'."
declare @strXml nvarchar(1000)
set @strXml = (select * from tblUsers where userId = 1225 for XML raw)
I'm developing a vb 2005 application and I€™m creating the users directly to the database. I want to assign them names.
I want to do something like this: CREATE TABLE admin.db_users ( id INT CONSTRAINT db_user_pk PRIMARY KEY, [name] VARCHAR(50) CONSTRAINT db_user_name_nn NOT NULL, authentication VARCHAR(25) CONSTRAINT db_user_authentication_nn NOT NULL, CONSTRAINT db_user_fk FOREIGN KEY(id) REFERENCES sys.database_principals (principal_id) ON UPDATE CASCADE ON DELETE CASCADE ); GO
This is the error that i'm getting: Msg 1767, Level 16, State 0, Line 1 Foreign key 'db_user_fk' references invalid table 'sys.database_principals'. Msg 1750, Level 16, State 0, Line 1 Could not create constraint. See previous errors.
How do I solve this problem or how can I do something similar.
Hi My webpage contain three dropdown box and one button. One dropdown to choose hospital_id, second dropdown to choose project_id and third dropdown to choose version_no .After choosing these three and when the button is clicked i want to run this sql query INSERT INTO version(project_id,hospital_id,date_created,comments) SELECT project_id,hospital_id,date_created,comments FROM version where version_no=@version_no and project_id=@project_id and hospital_id=@hospital_id. Just i need the code in asp.net 2.0 , VB , when the button is clicked the above query should run and the parameters (values) should take from dropdown box. Could anyone please send the solution for the above problem.
hi everybody I have the following asp.net2.0 codeSelectCommand = "Select IDEmp, FirstName,MiddleName,LastName, Date,HoursNumber, Description From Employee, WorkOnCategory , CatDesignItemReference where IDEmp =IDEmplWork AND FirstName = @FirstName AND Category = @AnyCategory AND ">
The problem is that the AnyCategory in my DropDownList1 refers to a key but unfortunalely my code understand it as string so it assigns Category = @AnyCategory as if Category ='AnyCategory ' not as Category = AnyCategory So what should I do Thanks
myConnection.Open() Dim myPuzzleCmd2 As New SqlCommand("GetRandomCode", myConnection)
myPuzzleCmd2.CommandType = CommandType.StoredProcedure Dim retLengthParam As New SqlParameter("@Length", SqlDbType.TinyInt, 6) retLengthParam.Direction = ParameterDirection.Input
myPuzzleCmd2.Parameters.Add(retLengthParam) Dim retRandomCode As New SqlParameter("@RandomCode", SqlDbType.VarChar, 30)
Try Dim reader As SqlDataReader = myPuzzleCmd2.ExecuteReader() myPuzzleCmd.ExecuteNonQuery()Catch ex As Exception
myPuzzleCmd2 = Nothing Session.Remove("RandomCode") HttpContext.Current.Session("RandomCode") = myPuzzleCmd2("@RandomCode") < --------- Over here Finally myConnection.Close() End Try
Hi I have add one new database mdf file in my project by ---> add new Item in to project. But This database.mdf file is in windows authetication mode. So there is no password assign to this. I want to assign use id and password to this database or I want to give sql server authetication mode. I have tried Modfy Connection property of database but that is not working. what is the default username of this conncetion????? REply.....
I have created a program that allow the user to register account as new user to sql. I do not want everyone use the same account (default sa).Now i want to group those users into one group which easy for management.But I cant find way to create new login group.I search over net, they said need to done under computer management--local user and group, but my computer do not have local user and group..
I am trying to automatically insert records into my existing customer table. Is there a way when I insert these new records and assign the customer number that it can sequentially pick the next available unique customer number for each record that is inserted? for example the first record would be customer number 100, the next 101, and so on? Please advise.
My issue is that I have 10 accounts that were assigned to 5 agents with each agent receiving 2 accounts. I would know like to randomly reassign the accounts with the only criteria being that the random allocation not reassign to the same agency and each agent gets 2 accounts again.
Data looks like below and I want to populate the randomly assigned agent in the "Second_Agent" column.
I have the qry, which is suppose to assigned records to active user (almost 15 users) equal, but it doesn’t- sometime it assigned more to some users and less to others. How could I modify my qry to make sure it assigns the records equals to each user? Please, see the qry below. I will appreciate any help
Thk
UPDATE TBLFRAUDFINDER SET DATE_ASSIGNED=GETDATE(), FRAUDANALYSTASSIGNED=@FRAUDANALYST WHERE FRAUDID=@FRAUDID OR (FRAUDANALYSTASSIGNED IS NULL AND ((INQUIRY_GOVT_NUMBER=@INQUIRY_GOVT_NUMBER) OR (CUST_NM=@CUST_NM) OR (ALERT_IDENTIFIER=@ALERT_IDENTIFIER) OR (ACCT IN (SELECT ACCT FROM TBLFRAUDFINDER WHERE INQUIRY_GOVT_NUMBER=@INQUIRY_GOVT_NUMBER OR CUST_NM=@CUST_NM OR ALERT_IDENTIFIER=@ALERT_IDENTIFIER))
Here is my issue. I have a list of merchants (generated daily) and Ineed to assign them eually to a set of analysts. Both the merchantlist and analyst list can change daily. I want to assign each merchantwith an analyst daily and need help to write out a stored procedurefor this (do not want to use VB).Here is relevant code for the tables:CREATE TABLE MerchList (MerchListID int IDENTITY (1, 1) NOT NULL ,FileDate datetime NOT NULL ,MerchID int NOT NULL ,AnalystID int NOT NULL ,)CREATE TABLE tblAnalyst (AnalystID int IDENTITY (1, 1) NOT NULL ,AnalystName varchar(100) NOT NULL)there will be about 10000 records in table MerchList and around 25records in table tblAnalyst.This will be used to assign work to analysts on a daily basis.Thanks for all your help!Vishal
I am trying to achieve a seemingly simple task of assigning datetime value to a user variable at the point my package starts running. How can I do this without using a SQL Script Task? Should I be using a script task for this or is there a simpler way to achieving the same thing?
im using the Northwind database, i use T-SQL commands to create a view that restricts users from seeing the address, city for all employees. i dont know how to assign the view to a user in the database using Enterprise manager. pls help me, im really needing a answer. thanks!
I deployed a clustering project. As a result, I got 10 clusters. Is there an automatic way to create a table with the customer ID and the cluster # that each customer was assigned to?
I have a column with int data type.. i am trying to assign this column to a variable ( int) in For Each Loop..but it keeps giving me an erro
The type of the value being assigned to variable "User:ubcontractor_Key" differs from the current variable type. Variables may not change type during execution. Variable types are strict, except for variables of type Object.
Am i getting this error becasue the column has NULL value?. how can I resove this probelm?