Placing Sp_executesql Data Into A Var
Jan 27, 2004
I have a stored procedure that takes various parameters and performs simple selects using these. A quick summary of the db structure this is working on would be :
lookup_table1
table1_id
description
lookup_table2
table2_id
description
This stored procedure attempts to select the given description from the given table and return the id, if the id isnt present it then inserts the new value and returns the new id.
Now I have this working, ish, but the problem that I have is that in the case of a new insert the procedure returns two datasets, an empty one (as the initial select returned no results) and another with the id of the newly inserted value.
This procedure as it stands right now
CREATE PROCEDURE aida_lookup
@lookup_table varchar(255),
@lookup_id_name varchar(255),
@lookup_description_col varchar(255),
@lookup_value varchar(255)
AS
declare @sql nvarchar(2048)
--
-- Check if the given lookup value exists in the give table / column
--
set @sql ='SELECT ' + @lookup_id_name + ' FROM ' + @lookup_table + ' WHERE ' + @lookup_description_col + ' = ''' + @lookup_value + ''''
EXECUTE sp_executesql @sql
if (@@rowcount = 0) goto new_value
if (@@error <> 0) goto on_error
return(1)
--
-- Insert new lookup value into the given table / column
--
new_value:
-- NEED TO CLEAR PREVIOUS NULL SELECT
begin transaction
set @sql = 'INSERT INTO ' + @lookup_table + ' (' + @lookup_description_col + ') VALUES (''' + @lookup_value + '''); SELECT SCOPE_IDENTITY()'
execute sp_executesql @sql
if (@@error <> 0) goto on_error
commit transaction
return(1)
--
-- Error handler
--
on_error:
rollback transaction
return (0)
GO
The problem being is that if the value is inserted as a new value I need to remove the empty dataset so that regardless of how the procedure is run, it will always return the id at position row 0 column 0.
My attempted solution was to declare a @temp var and place the return value of sp_executesql into this, and if it wasnt null then return it, and if it was then proceed to insert, e.g.
declare @temp int
...
SET @temp = EXECUTE sp_executesql @SQL
if (@@temp = null) goto new_value
SELECT @temp
return(1)
Obviously this doesnt work, so I am open to suggestions. To be completly honest I have run out of hair to rip out and I am sure this can probably be done in a much more elegant fashion, so any help will be greatly appreciated
View 11 Replies
ADVERTISEMENT
Mar 4, 2004
Hi, Gurus, I am running SQL-Server 2000 on SCSIIs with Raid-5. Three disks. I see only one Logical Disk with 3 partitions. Since it's recommended to have Log files seperate to Data files physicially, currently both exist in the D-Drive. How can it be accomplished?
Another question for ur kind suggestion. I have a merge-repl setup. Publisher and distributor at the same machine. One subscriber over the internet. Replication works through VPN rather that FTP. Whenever i apply SNAPSHOT it takes more that 12 hrs to replicate the 2 GB DB. Although VPN is more secured but the tunneling makes the replication rather slow i guess. Will there be a major difference if i open the default port of ftp on the ISA and change the subscriber to get the SNAPSHOT as Anonymous Subsciption. I mean What's better, Security VS Performance. During the SNAPSHOT the Web-users running on the Subscriber wait for the latest data which is very much annoying.
Another question please, I wanna replace the current publisher-DB machine with a new Hardware-Machine. I don't wanna lose Replication and re-running the SNAPSHOT. Is it possible to retain the publication by restoring the Master, Publication and Distributor respectively on the new machine. The new machine will have the same Operating system name and configuration.
Regards!!
View 3 Replies
View Related
Jul 23, 2005
This is a odd problem where a bad plan was chosen again and again, butthen not.Using the profiler, I identified an application-issued statement thatperformed poorly. It took this form:exec sp_executesql N'SELECT col1, col2 FROM t1 WHERE (t2= @Parm1)',N'@Parm1 int', @Parm1 = 8609t2 is a foreign key column, and is indexed.I took the statement into query analyzer and executed it there. Thequery plan showed that it was doing a scan of the primary key index,which is clustered. That's a bad choice.I then fiddled with it to see what would result in a good plan.1) I changed it to hard code the query value (but with the parmdefinition still in place. )It performed well, using the correct index.Here's how it looked.exec sp_executesql N'SELECT cbord.cbo1013p_AZItemElement.AZEl_Intid AS[Oid], cbord.cbo1013p_AZItemElement.incomplete_flag AS [IsIncomplete],cbord.cbo1013p_AZItemElement.traceflag AS [IsTraceAmount],cbord.cbo1013p_AZItemElement.standardqty AS [StandardAmount],cbord.cbo1013p_AZItemElement.Uitem_intid AS [NutritionItemOid],cbord.cbo1013p_AZItemElement.AZeldef_intid AS [AnalysisElementOid] FROMcbord.cbo1013p_AZItemElement WHERE (Uitem_intid= 8609)', N'@Parm1 int',@Parm1 = 8609After doing this, re-executing the original form still gave badresults.2) I restored the use of the parm, but removed the 'exec' from thestart.It performed well.After that (surprise!) it also performed well in the original form.What's going on here?
View 3 Replies
View Related
Apr 4, 2008
I can't get sp_executesql to accept more than 10 converted parameters in one execution. A stored procedure loops through a table variable that presents up to 100 parameters and their named data types. I've tried selecting into sql_variant and nvarchar variables and converting them to the named data type in the loop.
sp_executesql is outside the loop.
For the first 10 parameters sp_executesql recognizes the data type conversions of the variables that hold the parameter values, but then it fails to accept the conversions of the 11th and subsequent variables. Is there a limit to the number of conversions that sp_executesql can cope with?
View 5 Replies
View Related
Oct 13, 2006
Hi,
I am havin problems with the following giving a message
Msg 8114, Level 16, State 4, Line 0
Error converting data type varchar to datetime.
exec sp_executesql
@stmt=N'UPDATE CUSTOMER
SET [REQUEST] = @19, [DISC_EXPRY] = @28, [GROUP1] = @29, [GROUP2] = @31, [PR_LEVEL] = @48, [MOD_DATE] = @55, [MEM_CODE] = @63, [MEM_DATE] = @64, [HO_MOD] = @66, [LASTUPDATE] = @78
WHERE [ID] = @Old_1'
, @params=N'@19 nvarchar(4),@28 DateTime,@29 nvarchar(5),@31 nvarchar(5),@48 nvarchar(1),@55 DateTime,@63 nvarchar(7),@64 DateTime,@66 Integer,@78 Float,@Old_1 Integer',
@19= 'NRMA',@28= '1752-09-14',@29= 'ALBUM',@31= 'FRAME',@48= 'A',@55= '2006-10-10',@63= '1003.50',@64= '2006-10-10',@66= 3,@78= 39000.190633,@Old_1= 454636
however, as soon as I remove the datetime fields it works
exec sp_executesql
@stmt=N'UPDATE CUSTOMER
SET [REQUEST] = @19, [GROUP1] = @29, [GROUP2] = @31, [PR_LEVEL] = @48, [MEM_CODE] = @63, [HO_MOD] = @66, [LASTUPDATE] = @78
WHERE [ID] = @Old_1'
, @params=N'@19 nvarchar(4),@29 nvarchar(5),@31 nvarchar(5),@48 nvarchar(1),@63 nvarchar(7),@66 Integer,@78 Float,@Old_1 Integer',
@19= 'NRMA',@29= 'ALBUM',@31= 'FRAME',@48= 'A',@63= '1003.50',@66= 3,@78= 39000.190633,@Old_1= 454636
what am I doing wrong with the datetime parameters?
Grimhael
View 4 Replies
View Related
May 30, 2007
I have SQL 2005 Server and Visual Studio 2005 and I am working in vb. I want to create a database which has photographs.
View 3 Replies
View Related
May 19, 2008
Hi everyone, I have a small dilema here. I am running SSRS 2000, and I have a report that is grouped by Part Number. I have =Fields!Formula.Value < .1 so I can view only what is greater than .1 Well, my problem is that when I put it under the group Visibility properties, it does not pull all the data. and if i put it under detail Visibility. It does show me everything but any Part Number that is less than .1 shows just the part number but no detail. How can I make my report show all my data but without leaving data out????
Thanks ahead of time,
Abner
View 1 Replies
View Related
Mar 7, 2008
Do anyone know how I can automatically place a value eg. €œNOTHING€? in a database column when there is no or has a NULL value. Thanks.
View 2 Replies
View Related
May 29, 2007
hi all
i have a filed in my database with name address which contains addresses.
i want to split address in multiple line .
LIke
addressline1
addressline2
addressline3
i.e
Robart Peter
4th Banglow road
MC city
can any one help me.
View 4 Replies
View Related
Apr 17, 2008
Hi,
I am using Sql Server 2005.
I want to place a LOCK, insert something in the table then return back to the code (with the ID of the inserted item) and then call FUNCTION_A and then based on the outcome of the function I either want to
I want to keep the inserted item and release the lock or
I want to delete the inserted item and release the lock
Any suggestion is greatly appreciated.
Regards
naimulah
View 3 Replies
View Related
Jul 23, 1998
Our development server is limited on RAM and I have been asked to increase Tempdb. I made the decision to put it back on disk; something I have done dozens of times before. I have used the Enterprise Manager`s GUI interface and I have manually typed in the SQL using ISQL/w, both ways have resulted in the same error message.
Microsoft SQL-DMO
Error 5016: [SQL Server] Incorrect database name or device name(s).
I have dropped the old and created new database devices (with different names) and I still receive the error message. I have even tried rebooting with Tempdb back in RAM and on disk 1t 2MB (which works). And yes, I HAVE checked my typing.
I would GREATLY appreciate any ideas on what may be wrong. The system is 6.5 with SP4 on Win NT with SP3. I inherited the system, so I am not certain what the hisory is.
Thanks,
Mike Gaudet
Visages, Inc.
View 3 Replies
View Related
Nov 28, 2007
I'm generating emails using sp_send_dbmail. Everything works perfectly except for one thing. In the body of the email I need to show a link to a web page (eg http://myweb/login.aspx).
The problem is that the received email shows the "link" as plain text, ie it is not a clickable link. I've tried adding char(13) (and char(10) and both) after the link text but that doesn't help.
Is there a way to make the link text a real link when received by Outlook? (All recipients will be using Outlook if that helps).
Thanks,
John
View 6 Replies
View Related
Apr 3, 2007
I have created my packages and i want them to place them on the server.Do i need to place the entire project of dts packages on the server or is there any option to place executables...if so please explain....
And to run these packages on the server do i need to set them as new job at sql server agent or is there any other way i need to run on the server.
I want then to run whenever the text file gets updated is it possible to set anything for my packages to run as and when the text file gets updated..
Please help me with all my questions
Thanks in advance..
View 5 Replies
View Related
Jan 30, 2007
I have been requested to add the sum of an interger field to the table header. I have the sum in the footer (which is very easy to do), but I cannot get the sum to appear in the table header.
I then set-up the stored procedure to run the sum, and place it into a dummy field. I still cannot add this field to the table header. Instead of printing the data for the dummy field (the correct total), it instead prints the actual field name on the report.
Is there anyway to place a sum in a table header on a SQL Server Report?
Let me know.
Thank you,
T.J.
View 7 Replies
View Related
Jan 4, 2008
Hi,
After exporting the report the column headers in the rreport should not scroll, it has to fix with report headers. If i move the column headers to report header the columns are merging in excel, some columns are hiding.
For ex: I have 10 columns, it has to take from A to K but it is taking A to P. one column is occupying two columns. how to avoid this merging and how to place the column headers in the report header.
Thanks
Dinesh
View 4 Replies
View Related
Jan 29, 2008
I have a define formula that is SUM(Loan Loan Amount[2]) and this formula has a addition filter off of it.
The report is pulling off of calander months months so if in some of the fields it has a dollar amount but in others it is blank. Trying to write formula that if there is no amount then place zero otherwise put the $ amount.
thanks
View 1 Replies
View Related
Jan 9, 2008
Hi. I have an sql query that i use to insert articles to a sql databse table and for that i use addWithValue to select witch textboxes etc goes where in the database.
Now i need to retrive these values and place them back into some other textboxes (some of them multiline) ,and i wonder if there are any similar ways to retrive values like AddWithparameter so i can easily do textBox.text = //whatever goes here ?
View 4 Replies
View Related
Feb 29, 2008
I am working on a form that when text is entered, the action Page is to execute the following query:
SELECT PhList.Name AS Employee, PhList.Phone, Department.Name, PhList.JobTitle FROM PhList INNER JOIN Department ON PhList.Department = Department.ID WHERE (PhList.Name LIKE @Search) OR (PhList.Phone LIKE @Search) OR (Department.Name LIKE @Search)"
BUT... i am having trouble making my @Search Parameter = %value% (where only 'value' was typed into the original form)
Here is my SQLDataSourceCode...<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:Intranet %>"
SelectCommand="SELECT PhList.Name AS Employee, PhList.Phone, Department.Name, PhList.JobTitle FROM PhList INNER JOIN Department ON PhList.Department = Department.ID WHERE (PhList.Name LIKE @Search) OR (PhList.Phone LIKE @Search) OR (Department.Name LIKE @Search)"
OnSelecting="SqlDataSource1_Selecting">
<SelectParameters>
<asp:QueryStringParameter Name="Search" QueryStringField="Search" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
here is my Selecting code... Protected Sub SqlDataSource1_Selecting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.SqlDataSourceSelectingEventArgs) e.Command.Parameters("Search").Value = "%" & Request.QueryString("Search") & "%" End Sub
The error i am getting is...
An SqlParameter with ParameterName 'Search' is not contained by this SqlParameterCollection. (From the e.command.par.........)
View 2 Replies
View Related
Apr 7, 2008
I've read that if particular tables are frequently queried together through a join then these tables should be placed on different devices on different physical disks.
What does this mean exactly and how would you configure this?
Is this a common practice in high-performance real-world environments (or should it be)?
View 3 Replies
View Related
Oct 6, 2004
I am working on deploying my production DB's to a new server and am looking for some advice. The new server is running RAID-5 (the old one is RAID-0) but it only has one controller therefore I can not create another array group. So I was wondering since the disk setup is C: and D: (Virtual Drive) if I would see any benefits from placing my log files on C: and my Data files on D:?
The other question is related to the size of my log files. Some of the DB's were not created by me and there are no constraints in log file growth causing some very large TRANS logs. For example, there is a 100 MB DB with a 1 GB trans log. I restored the DB on my new server and truncated the log file (manually, the Ent Mgr Shrink DB tool doesn't work worth a hoot) to half the size of the DB and it functions properly. I was just wondering if this would cause any problems down the road if I did all of my DB's like this?
I am restricting log file growth to approximately half the size of the DB.
There is one DB that is 1.5 GB and the log file was set restricted to 2mb and it works fine, but I feel that I should bump this up a bit.
Any recommendations?
View 10 Replies
View Related
Mar 5, 2005
Hi,
I know that SQL Server (MSDE), databases run much faster when the data and log files are on seperate physical devices. I can do this explictly when I write a CREATE DATABASE SQL script, but would like to change the MODEL database so that all new databases use the sperate data/log file assignments by default. I haven't found a way to alter the sysfiles table in model - I can read the data, but it balks at trying to update it. (recordset is not updateable, or adhoc querries not allowed against a system database).
I didn't see any options on the MSDE install that implements seperate data/log paths.
I don't have the SQL Server tools (like Enterprise Manager) available, but I do have VS.NET 03 (Standard). And Web Data Administrator.
Any suggestions? Thanks in advance.
View 5 Replies
View Related
Apr 26, 2000
Anyone know how to place additional indexes on system tables?
View 1 Replies
View Related
Jul 20, 2005
Hello folks,first of all I really don't know how you gurus call this way ofwriting joins:SELECTA.FIELD,B.FIELDFROMTABLE_A A,TABLE_B BWHEREA.ID_FIELD = B.ID_FIELDI find this way very useful and readable. It works also with left andright Joins (using *= or =* instead of = )A friend of mine found that the inner join way (using = ) in Access ismuch more slower than using the classic INNER JOIN TABLE ON FIELDsintax. My question is: was MSSQL Server studied for using the shortway, or it is just a workaround found by someone? Is there aperformance degrade folllowing this way?TIA,tK
View 1 Replies
View Related
Apr 27, 2015
I have a question regarding saving hashtags in another table. I have two tables with these columns:
Table1
ItemId, Name, Description (it may contains several hashtags like this example "hey I am an #example of this #question")
Table2
HashtagId, ItemId, Hashtag
So I want to detect #example and #question and put them in Table2. I'd like to create a trigger for table1 that if there was a hashtag, it added a record in table 2.
CREATE TRIGGER [dbo].[tr_Events_ForInsert_Hashtag]
ON Table1
FOR INSERT
AS
BEGIN
DECLARE @ItemId bigint
SELECT @ItemId = ItemId FROM inserted
[Code] .....
View 3 Replies
View Related
Dec 17, 2007
Hi everyone, I have created a matrix report which takes 3 parameters being store, year and quarter which then displays budget information in a matrix. This all works fine but I would also like to have a bar chart below the matrix to visually show the results.
However when I add the bar chart and add the relevent dataset details etc the chart does not appear when I preview the report. I wondered if the chart wasn't showing because the parameter values are not being passed to the chart.
Has anybody any idea of adding charts to reports in this way or knows of any instructions to do so.
Thanks
Sally
View 3 Replies
View Related
Mar 2, 2007
This one is driving me crazy. I have followed several steps given in examples both online and in the four SRS books I own to no avail. I have created a new report.rdl template and have all the required features for our company needs, except placing the company logo as a background image in watermark style (similar to the Company Sales report that comes with the SRS report samples). I right-click on the body and in properties set the image name (URHCSlogo), it defaults to external, but I can not get it to be embedded and it will not let me set the mimetype. Could someone please give me a step-by-step method to do this? Thanks!
View 5 Replies
View Related
Apr 20, 2001
We are in the process of replacing our primary production server. In the process of determining how SQL server is going to be structured, it has been suggested that I place all current and new indexes on a separate file group. These filegroups would then reside on a separate shelf on the server. What are the pros and cons of doing this?
View 2 Replies
View Related
Jul 4, 2007
Hi,
If I am taking a Matrix and right clicking on the column header and click on the SubTotal then it always place that column on the right of it .If I want to place that column to the left of my original column then I can't do it.
Adding manual column and then puuting the Expresstion =Sum(Fields!MyCol.Value) is not halping as it will give me the same value that is there in the column instead of giving me the column
-Thanks,
Digs
View 1 Replies
View Related
Jan 8, 2008
Hi,
I am novice to SQL reporting services.
I have created a report using SSRS.
In this report I would like to show a column value as button and wants to execute vbscript code on click.
Or at least execute vbscript code on click of that field (button is just an option!)
The code will launch another application (exe file or else)
Help in this regard would be appreciated.
Thanks
View 2 Replies
View Related
Jul 31, 2006
I have been trying to get my dynamic query to work with sp_executesql and I cant seem to figure out this one issue.DECLARE @SQL NVARCHAR(1000)SET @SQL = N'WITH Data AS(SELECT Id, Username, FirstName, LastName, Email, LastLogin, ROW_NUMBER() OVER(ORDER BY @SortExpression) AS RowNumber FROM Users) SELECT * FROM Data WHERE RowNumber BETWEEN @Between1 AND @Between2'EXECUTE sp_executesql @SQL, N'@SortExpression VARCHAR(50), @Between1 INT, @Between2 INT', @SortExpression = 'Email', @Between1 = 1, @Between2 = 10As you can see, the data should get sorted by the value of @SortExpression. However thats not the case. The Data does not get sorted at all no matter that i pass in as the value of @SortExpression.I can't seem to figure out why its not working.
View 2 Replies
View Related
Aug 8, 2005
What is wrong in this query..how can I make it to work
DECLARE @strSQL nVarchar(4000)
DECLARE @Name VArchar(100)
--SET @Name = '''sysdatabase'',''sysindexes'''
SET @Name = ''sysdatabase''
SET @strSQL = 'SELECT * FROM dbo.sysobjects WITH (NOLOCK) WHERE Name IN (@prmName)'
EXECUTE dbo.sp_executesql @strSQL,
N'@prmName varchar(100)',
@prmName= @Name
Note : I do not want to replace the query as
SET @strSQL = 'SELECT * FROM dbo.sysobjects WITH (NOLOCK)
WHERE Name IN ' + @Name + ')' , because my queryplan changes if I do this.
Any work around or anything you guys suggest ..
Thanks.
View 2 Replies
View Related
Feb 27, 2008
I'm having trouble working out why the sp_executesql procedure is not replacing my place holders with the value assigned to it.
Some quick info: I'm running the routine from the commandline through OSQL on a box that has MSSQL2000 enterprise installed. The code is sent to a MSSQL2005 box.
I've noticed one dumb thing I've done and that is making the nvarchar variable @db_name a different size to the one declared in the sp_executesql command. But I'm not sure if that is the problem. It throws a @db_name is not a database error etc.
Snippet that is not working:
declare @db_name varchar(80)
declare @sql_command nvarchar(1500)-- for our dynamic sql command within the cursor loop.
fetch
next
from
settings_cursor
into
@db_name
while
@@fetch_status = 0
begin
print 'CHECKING DBOPTIONS FOR ' + @db_name + ' - ( CHECKSUM, CREATE & UPDATE STATS, FULLRECOVERY)'
set @sql_command ='select'
set @sql_command = @sql_command + 'count(*)'
set @sql_command = @sql_command + 'from'
set @sql_command = @sql_command + 'sys.databases'
set @sql_command = @sql_command + 'where'
set @sql_command = @sql_command + 'name = ''@db_name'''
set @sql_command = @sql_command + 'and'
set @sql_command = @sql_command + 'page_verify_option_desc = ''checksum'''
set @sql_command = @sql_command + 'and'
set @sql_command = @sql_command + 'is_auto_create_stats_on = 1'
set @sql_command = @sql_command + 'and'
set @sql_command = @sql_command + 'is_auto_update_stats_on =1'
set @sql_command = @sql_command + 'and'
-- select recovery model based upon database name.
if @db_name = 'DBAdmin'
or @db_name = 'Master'
or @db_name = 'Model'
or @db_name = 'msdb'
begin
set @sql_command = @sql_command + 'recovery_model_desc = ''simple'''
end
else
begin
set @sql_command = @sql_command + 'recovery_model_desc = ''full'''
end
-- include db chaining for Master database
if @db_name = 'Master'
begin
set @sql_command = @sql_command + 'and'
set @sql_command = @sql_command + 'is_db_chaining_on = 1'
end
-- execute sql command.
--print @sql_command
declare @count int
execute @count = sp_executesql @sql_command, N'@db_name nvarchar(20)',@db_name=@db_name
if @count = 0-- no records were returned as the settings were wrong.
begin
select 'Issue with settings. altering now'
if @db_name = 'DBAdmin'
or @db_name = 'Master'
or @db_name = 'Model'
or @db_name = 'msdb'
begin
alter database [@db_name] set recovery simple
alter database [@db_name] set page_verify checksum
end
else
begin
alter database [@db_name] set recovery full
alter database [@db_name] set page_verify checksum
end
if @db_name = 'msdb'
begin
alter database [@db_name] set db_chaining on
end
-- all databases get these switched on
alter database [@db_name] set auto_create_statistics on
alter database [@db_name] set auto_update_statistics on
end
else
begin
select 'all settings for ' + @db_name + ' are good'
end
fetch next from settings_cursor into @db_name
end
-- clean up
close settings_cursor
deallocate settings_cursor
View 3 Replies
View Related
Jan 18, 2002
Hi
I am trying to execute sp_executesql dynamically. What I am trying to do is read all the user tables using a cursor build sql statement and using
EXEC sp_execute sqlstmt.
Here is piece of code.
DECLARE C1 CURSOR FOR SELECT NAME FROM SYSOBJECTS WHERE XTYPE='U'
OPEN c1
FETCH NEXT FROM C1 INTO @v_TableName
WHILE @@FETCH_STATUS = 0
BEGIN
SELECT @v_SQL= 'DROP TABLE ' + @v_TableName
--EXEC @v_SQL
PRINT @v_SQL
IF @v_Error<>0
BEGIN
SELECT @ErrorCount=@ErrorCount+1
PRINT 'ERROR OCCURED WHILE DROPING TABLE ' + @v_TableName
--GOTO ErrorHandler
END
FETCH NEXT FROM C1 INTO @v_TableName
END
CLOSE c1
DEALLOCATE C1
Please let me know where I am doing wrong.
Thanks,
Rau
View 1 Replies
View Related