Wednesday, March 23, 2011

#temp table or a @table variable

In a stored procedure, you often have a need for storing a set of data within the procedure, without necessarily needing that data to persist beyond the scope of the procedure. If you actually need a table structure, there are basically four ways you can "store" this data: 


1.local temporary tables (#table_name), 
2.global temporary tables (##table_name),
3.permanent tables (table_name), and
4.table variables (@table_name). 




Local Temporary Tables :
 

CREATE TABLE #people 

    id INT, 
    name VARCHAR(32) 
)


A temporary table is created and populated on disk, in the system database tempdb
The data in this #temp table (in fact, the table itself) is visible only to the current scope (usually a stored procedure, or a set of nested stored procedures). The table gets cleared up automatically when the current procedure goes out of scope, but you should manually clean up the data when you're done with it: 
 

DROP TABLE #people
EXAMPLE:

CREATE TABLE #TibetanYaks(
YakID int,
YakName char(30) )

INSERT INTO #TibetanYaks (YakID, YakName)
SELECT  YakID, YakName
FROM  dbo.Yaks
WHERE  YakType = 'Tibetan'

-- Do some stuff with the table

drop table #TibetanYaks



Table Variables  :
A table variable is created in memory, and so performs slightly better than #temp tables
1.Table variables don't need to be dropped when you are done with them.
2.If you have less than 100 rows generally use a table variable.  Otherwise use  a temporary table.  This is because SQL Server won't create statistics on table variables.
3.Table variables are automatically cleared when the procedure or function goes out of scope, so you don't have to remember to drop or clear the data (which can be a good thing or a bad thing; remember "release early"?).
4.Table variables are the only way you can use DML statements (INSERT, UPDATE, DELETE) on temporary data within a user-defined function. You can create a table variable within a UDF, and modify the data using one of the above statements. For example, you could do this: 
5.we can use the  temporary table  with in function



DECLARE @people TABLE 

    id INT, 
    name VARCHAR(32) 
)






CREATE FUNCTION dbo.example1 


RETURNS INT 
AS 
BEGIN 
    DECLARE @t1 TABLE (i INT) 
    INSERT @t1 VALUES(1) 
    INSERT @t1 VALUES(2) 
    UPDATE @t1 SET i = i + 5 
    DELETE @t1 WHERE i < 7 
 
    DECLARE @max INT 
    SELECT @max = MAX(i) FROM @t1 
    RETURN @max 
END 
GO





DECLARE @TibetanYaks TABLE (
YakID int,
YakName char(30) )

INSERT INTO @TibetanYaks (YakID, YakName)
SELECT  YakID, YakName
FROM  dbo.Yaks
WHERE  YakType = 'Tibetan'

-- Do some stuff with the table 

DECLARE @TibetanYaks TABLE (
YakID int,
YakName char(30) )

INSERT INTO @TibetanYaks (YakID, YakName)
SELECT  YakID, YakName
FROM  dbo.Yaks
WHERE  YakType = 'Tibetan'

UPDATE  @TibetanYaks
SET  YakName = UPPER(YakName)

SELECT *
FROM @TibetanYaks

Thursday, March 17, 2011

How "Execute SQL Task Work" ?

#Case 1:Simply execute the SQL query which will return the records:
Steps: Execute SQL Task Editor:----->Result Set(None)-------->SQL Statement --->direct input(select time_key from dw.Dim_Date).
#Case 2:Pass the parameter into the Execute sql task and get the records and store the data in to the result set:
Steps:declare variable which u want to pass here "datechk" .
result set:single Row(it will store the single row)
SQL Statement: write a query

if exists (select 'X' from dw.Dim_Date where date_key = ?)
BEGIN
  select 'True' AS date_key
END
ELSE
BEGIN
select 'False' AS date_key
END
what ever value you want to pass should be represent through (?) question marks.


add the variable in the "parameter mapping" .this variable contains the value which you want to pass.


create the result set Note:the result set name "date_key" should be same in the sql Query.


SSIS Script task(C# code)

#Declare the variable("myVariable") of string type for package level and update the variable value using the script task.
Follow the Steps:
Step1:Add the variable "myVariable"  in the script task editor under "ReadWriteVariables".Please Note that the variable name is case sensitive.
Step2:click on edit script:
Dts.Variables["myVariable"].Value = "hello world";
output: "hello world" will assign to the variable "my Variable"
****************************************************************
#Display the variable value in to the message box:
MessageBox.Show(Dts.Variables["myVariable"].Value.ToString());
output: It will show you the messagebox with"hello world".
*****************************************************************
#Get the substring  form the variable myVariable which contains "hello world" string.
MessageBox.Show(Dts.Variables["var2"].Value.ToString().Substring(0, 5););
output:It will display the messagebox with "hello" string.
******************************************************************
#How to pass parameters in the store procedure from the Script task?
Find the Code Below:
private void LogFileNameEx(string strFileName, bool bSuccess, string strMessage)
        {
OleDbConnection sqlConnection = new OleDbConnection(Dts.Connections["TFOWarehouse"].ConnectionString);
//TFO Warehouse is the connection manager

            using (OleDbCommand cmdUspFileProcessingDetailsOnBegin = new OleDbCommand("MD.usp_GetFileProcessingList"))
            {
                cmdUspFileProcessingDetailsOnBegin.Connection = sqlConnection;
                cmdUspFileProcessingDetailsOnBegin.CommandType = CommandType.StoredProcedure;
                cmdUspFileProcessingDetailsOnBegin.Parameters.Add("@pExecutionLogId", SqlDbType.Int).Value = Dts.Variables["LogID"].Value;
                cmdUspFileProcessingDetailsOnBegin.Parameters.Add("@pFileType", SqlDbType.VarChar).Value = Dts.Variables["FileNameTemplate"].Value;
                cmdUspFileProcessingDetailsOnBegin.Parameters.Add("@pFileName", SqlDbType.VarChar).Value = strFileName;
                cmdUspFileProcessingDetailsOnBegin.Parameters.Add("@pMessage", SqlDbType.VarChar).Value = strMessage;
                if (bSuccess)
                    cmdUspFileProcessingDetailsOnBegin.Parameters.Add("@pExtractDate", SqlDbType.DateTime).Value = dtFileExtract;
                else
                    cmdUspFileProcessingDetailsOnBegin.Parameters.Add("@pExtractDate", SqlDbType.DateTime).Value = DBNull.Value;
                try
                {
                    sqlConnection.Open();
                    cmdUspFileProcessingDetailsOnBegin.ExecuteNonQuery();
                }
                finally
                {
                    sqlConnection.Close();
                    sqlConnection.Dispose();
                }
            }
        } 


The store procedure structure is below:



ALTER PROCEDURE [MD].[usp_GetFileProcessingList]    
 @pExecutionLogId  INT    
 ,@pFileType   VARCHAR(255)    
 ,@pFileName   VARCHAR(255)    
    ,@pMessage          VARCHAR(255) = NULL    
    ,@pExtractDate  DATETIME = NULL  
WITH EXECUTE AS CALLER    
AS    
BEGIN    
 SET NOCOUNT ON    
 IF @pExtractDate IS NU



The parameter name should be same.
******************************************************************************

Tuesday, March 1, 2011

Errors During Configure Reporting Server(SQLServer2008R2)


Error:Network permission while opening of report manager
Solution:Open IE-->Tool-->Internet Options-->security--->Trusted Sites---->Click Sites Tab-->add http://servername and check "require server verification(https:) for all sites in the Zone" check box.


Error:The permissions granted to user 'domain\username' are insufficient for performing this operation."
Solution:change the security level to "0"(zero).
.....\Program Files\SQL Server 2008\MSRS10_50.MSSQLSERVER\Reporting Services\ReportServer\ReportServer.config


<Add Key="SecureConnectionLevel" Value="0"/>

By default the secure connection Level is "2",make it to "Zero"

Error:User 'bvp-PC\bvp' does not have required permissions. Verify that sufficient permissions have been granted and Windows User Account Control (UAC) restrictions have been addressed

solution:
  1. Configure the report server for local administration. To access the report server and Report Manager locally, follow these steps:
  2. Start Windows Internet Explorer.
  3. On the Tools menu, click Internet Options.
  4. Click Security.
  5. Click Trusted Sites.
  6. Click Sites.
  7. Under Add this Web site to the zone, type http://<var>ServerName</var>. If you are not using HTTPS for the default site, click to clear the Require server certification (https:) for all sites in this zone check box.
  8. Click Add.
  9. Repeat step 7f and step 7g to add the http://localhost URL, and then click Close.
  10. Note This step enables you to start Internet Explorer and open either the localhost or the network computer name of the server for both the Report Server application and the Report Manager application.
  11. Create role assignments that explicitly grant you access together with full permissions. To do this, follow these steps:
  12. Start Internet Explorer together with the Run as administrator option. To do this, click Start, click All Programs, right-clickInternet Explorer, and then click Run as administrator.
  13. Open Report Manager. By default, the Report Manager URL is http://<var>ServerName</var>/reports.

    If you use SQL Server Express with Advanced Services SP2, the Report Manager URL is http://<var>ServerName</var>/reports$sqlexpress. If you use a named instance of Reporting Services, the Report Manager URL is http://<var>ServerName</var>/reports$<var>InstanceName</var>
  14. In the Home dialog box, click Properties.
  15. Click New Role Assignment.
  16. Type a Windows user account name by using the following format:
    <var>Domain</var>\<var>User</var>
  17. Click to select the Content Manager check box.
  18. Click OK.
  19. In the Home dialog box, click Site Settings.
  20. Click Configure site-wide security.
  21. Click New Role Assignment.
  22. Type a Windows user account by using the following format:
    <var>Domain</var>\<var>User</var>
  23. Click System Administrator.
  24. Click OK.
  25. Close Report Manager.
  26. Use Internet Explorer without the Run as administrator option to reopen Report Manager.


Errors: The request failed with HTTP status 502 :proxy error(No data record is avaliable)  while deploying reports in the reporting server:

solution:1.     Go to 'Tools -> Options'
2.     Go to 'Environment -> Web Browser'
3.     Click on 'Internet Explorer Options' button
4.     Navigate to 'Connections', click 'LAN Settings'
5.     Check if a proxy server set under "Use a proxy server for your LAN...." check box. If this value is not set:
1.     Check the above checkbox
2.     Specify a proxy server and port
3.     Check "Bypass proxy for local addresses"
4.     Click 'Ok', 'Ok' and 'Ok' to complete the settings.