How to Query the multiple values of same coulmn in sqlserver 2008? - sql-server-2008

MY Table like this:
id Tag platform
1 #class1,#class2 CS
2 #class1 PS
3 #class2 CS
if i pass "'#class1'" as parameter to SP getting only one record that is 2nd record.But need to 1st and 2nd records because #class1 contains in both 1,2 rows.Please tell me how to write this.I am using IN statement as of now.By using getting only record.
MY SP:
ALTER PROCEDURE [dbo].[usp_Get]-- 1,"'#class1,#class2'"
#Appid INT,
#TagList NVARCHAR (MAX)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
SELECT #TagList = '%' + RTRIM(LTRIM(#TagList)) + '%';
declare #tags varchar(MAX)
set #tags = #TagList
create table #t (tag varchar(MAX))
set #tags = 'insert #t select ' + replace(#tags, ',', ' union select ')
exec(#tags)
Select
id FROM dbo.List WHERE ((appid=#Appid)) AND ((Tags LIKE(select tag from #t)
END
How to modify please tell me...
Thanks in advance..

One solution would be to use LIKE operator in your stored procedure:
CREATE PROCEDURE FindTag #TagName char(50)
AS
SELECT #TagName = '%' + TRIM(#TagName) + '%';
SELECT Tag
FROM MyTable
WHERE Tag LIKE #TagName;
GO

Related

SQL method for returning data from multiple tables based on column names

I am trying to do something a little weird and cannot figure out the right method for getting it done. Essentially I am trying to pull all tables/views and columns where the column name is like some string. In addition to that I would like to pull 1 row of data from that table/view and column combination. The second part is where I am lost. I know I can pull the necessary tables/views and columns with the below select statement.
SELECT COLUMN_NAME AS 'ColumnName'
,TABLE_NAME AS 'TableName'
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME LIKE '%email%'
ORDER BY TableName,ColumnName;
So that I get something like the below
|ColumnName |TableName |
|emailAddress |all_emails |
....
But I want to get something like this:
|ColumnName |TableName |Example |
|emailAddress |all_emails |first.last#gmail.com|
....
Can anyone offer any insight?
I can't think of a simple way to do this within a query, but here's one option...
Put the list of the columns and tables into a temp table and run them through a loop, using dynamic SQL to select the max row for each.
I've added plenty of comments below to explain it.
DECLARE #SQL NVARCHAR(1000)
DECLARE #TABLE NVARCHAR(1000)
DECLARE #COLUMN NVARCHAR(1000)
DECLARE #SAMPLE NVARCHAR(1000)
DROP TABLE IF EXISTS ##TABLELIST
SELECT COLUMN_NAME AS 'ColumnName'
,TABLE_NAME AS 'TableName'
,ROW_NUMBER() OVER (ORDER BY COLUMN_NAME,TABLE_NAME)[RN]
INTO ##TABLELIST
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME LIKE '%email%';
ALTER TABLE ##TABLELIST
ADD [Sample] NVARCHAR(1000) -- Add a column for your sample row.
DECLARE #ROWCOUNTER INT = 1 -- Add a counter for the loop to use.
WHILE #ROWCOUNTER <= (SELECT MAX([RN]) FROM ##TABLELIST) -- Keep the loop running until the end of the list.
BEGIN
UPDATE ##TABLELIST
SET #TABLE = TableName WHERE [RN] = #ROWCOUNTER -- Get the table name into a variable.
UPDATE ##TABLELIST
SET #COLUMN = ColumnName WHERE [RN] = #ROWCOUNTER -- Get the column name into a variable.
SET #SQL = 'SELECT #SAMPLE = MAX([' + #COLUMN + ']) FROM [' + #TABLE + ']' -- Create SQL statement to pull max column from table specified in variables.
EXEC SP_EXECUTESQL #SQL, N'#SAMPLE NVARCHAR(1000) OUTPUT', #SAMPLE OUTPUT -- Execute SQL and put the output into the #SAMPLE variable.
UPDATE ##TABLELIST
SET [Sample] = CAST(#SAMPLE AS NVARCHAR(1000)) WHERE [RN] = #ROWCOUNTER -- Insert the SQL output into the sample column.
SET #ROWCOUNTER = #ROWCOUNTER+1 -- Add one to the row counter to move to the next column and table.
END
SELECT * FROM ##TABLELIST -- Select final output.

Adding table style in this stored procedure?

The other day I found a great stored procedure in this symantec link that converts the results of a TSQL table into an HTML table. Without any CSS parameters, the result works great. I tend to send tons of emails with SQL server results, so this is very helpful.
Now that I was able to make it work, I'm trying to add some style to the table. The problem is that I'm not sure how sending the CSS class as parameter works.
For example, here's how I should call the SP:
EXEC dbo.CustomTable2HTMLv3 'Buffy',#HTML1 OUTPUT,'class="horizontal"',0
The problem is that I have no idea where the CSS class horizontal comes from. In the link I can see the actual CSS, but how does the stored procedure read this?
The css looks like this:
table.horizontal tr:first-child {
background-color: Gray!important;
font-weight: bold;
color: #fff;
}
And this is the stored procedure:
CREATE PROCEDURE [dbo].[CustomTable2HTMLv3] (
#TABLENAME NVARCHAR(500),
#OUTPUT NVARCHAR(MAX) OUTPUT,
#TBL_STYLE NVARCHAR(1024) = '',
#ALIGNMENT INT =0 )
AS
-- Author: Ian Atkin (ian.atkin#ict.ox.ac.uk)
-- Description
-- Stored Procedure to take an arbitraty temporary table and return
-- the equivalent HTML string .
-- Version History
-- 1.0 - v1 Release For Symantec Connect
-- 3.0 - v3 Release for Symantec connect.
-- Table to be outputed both horizonally and vertically. IsNull used
-- on cell value output to prevent NULLs creaping into HTML string
-- #exec_str stores the dynamic SQL Query
-- #ParmDefinition stores the parameter definition for the dynamic SQL
DECLARE #exec_str NVARCHAR(MAX)
DECLARE #ParmDefinition NVARCHAR(500)
IF #ALIGNMENT=0
BEGIN
--We need to use Dynamic SQL at this point so we can expand the input table name parameter
SET #exec_str= N'
DECLARE #exec_str NVARCHAR(MAX)
DECLARE #ParmDefinition NVARCHAR(500)
DECLARE #DEBUG INT
SET #DEBUG=0
IF #DEBUG=1 Print ''Table2HTML -Horizontal alignment''
--Make a copy of the original table adding an indexing column. We need to add an index column to the table to facilitate sorting so we can maintain the
--original table order as we iterate through adding HTML tags to the table fields.
--New column called CustColHTML_ID (unlikely to be used by someone else!)
--
select CustColHTML_ID=0,* INTO #CustomTable2HTML FROM ' + #TABLENAME + '
IF #DEBUG=1 PRINT ''Created temporary custom table''
--Now alter the table to add the auto-incrementing index. This will facilitate row finding
DECLARE #COUNTER INT
SET #COUNTER=0
UPDATE #CustomTable2HTML SET #COUNTER = CustColHTML_ID=#COUNTER+1
IF #DEBUG=1 PRINT ''Added counter column to custom table''
-- #HTMLROWS will store all the rows in HTML format
-- #ROW will store each HTML row as fields on each row are iterated through
-- using dymamic SQL and a cursor
-- #FIELDS will store the header row for the HTML Table
DECLARE #HTMLROWS NVARCHAR(MAX) DECLARE #FIELDS NVARCHAR(MAX)
SET #HTMLROWS='''' DECLARE #ROW NVARCHAR(MAX)
-- Create the first HTML row for the table (the table header). Ignore our indexing column!
SELECT #FIELDS=COALESCE(#FIELDS, '' '','''')+''<td>'' + name + ''</td>''
FROM tempdb.sys.Columns
WHERE object_id=object_id(''tempdb..#CustomTable2HTML'')
AND name not like ''CustColHTML_ID''
SET #FIELDS=#FIELDS + ''</tr>''
IF #DEBUG=1 PRINT ''table fields: '' + #FIELDS
-- #ColumnName stores the column name as found by the table cursor
-- #maxrows is a count of the rows in the table, and #rownum is for marking the
-- ''current'' row whilst processing
DECLARE #ColumnName NVARCHAR(500)
DECLARE #maxrows INT
DECLARE #rownum INT
--Find row count of our temporary table
SELECT #maxrows=count(*) FROM #CustomTable2HTML
--Create a cursor which will look through all the column names specified in the temporary table
--but exclude the index column we added (CustColHTML_ID)
DECLARE col CURSOR FOR
SELECT name FROM tempdb.sys.Columns
WHERE object_id=object_id(''tempdb..#CustomTable2HTML'')
AND name not like ''CustColHTML_ID''
ORDER BY column_id ASC
--For each row, generate dymanic SQL which requests the each column name in turn by
--iterating through a cursor
SET #rowNum=1
SET #ParmDefinition=N''#ROWOUT NVARCHAR(MAX) OUTPUT,#rowNum_IN INT''
While #rowNum <= #maxrows
BEGIN
SET #HTMLROWS=#HTMLROWS + ''<tr>''
OPEN col
FETCH NEXT FROM col INTO #ColumnName
IF #DEBUG=1 Print ''#ColumnName: '' + #ColumnName
WHILE ##FETCH_STATUS=0
BEGIN
--Get nth row from table
--SET #exec_str=''SELECT #ROWOUT=(select top 1 ['' + #ColumnName + ''] from (select top '' + cast(#rownum as varchar) + '' * from #CustomTable2HTML order by CustColHTML_ID ASC) xxx order by CustColHTML_ID DESC)''
SET #exec_str=''SELECT #ROWOUT=(select ['' + #ColumnName + ''] from #CustomTable2HTML where CustColHTML_ID=#rowNum_IN)''
IF #DEBUG=1 PRINT ''#exec_str: '' + #exec_str
EXEC sp_executesql
#exec_str,
#ParmDefinition,
#ROWOUT=#ROW OUTPUT,
#rowNum_IN=#rownum
IF #DEBUG=1 SELECT #ROW as ''#Row''
SET #HTMLROWS =#HTMLROWS + ''<td>'' + IsNull(#ROW,'''') + ''</td>''
FETCH NEXT FROM col INTO #ColumnName
END
CLOSE col
SET #rowNum=#rowNum +1
SET #HTMLROWS=#HTMLROWS + ''</tr>''
END
SET #OUTPUT=''''
IF #maxrows>0
SET #OUTPUT= ''<table ' + #TBL_STYLE + '>'' + #FIELDS + #HTMLROWS + ''</table>''
DEALLOCATE col
'
END
ELSE
BEGIN
--This is the SQL String for table columns to be aligned on the vertical
--So we select a table column, and then iterate through all the rows for that column, this forming
--one row of our html table.
SET #exec_str= N'
DECLARE #exec_str NVARCHAR(MAX)
DECLARE #ParmDefinition NVARCHAR(500)
DECLARE #DEBUG INT
SET #DEBUG=0
IF #DEBUG=1 Print ''Table2HTML -Vertical alignment''
--Make a copy of the original table adding an indexing column. We need to add an index column to the table to facilitate sorting so we can maintain the
--original table order as we iterate through adding HTML tags to the table fields.
--New column called CustColHTML_ID (unlikely to be used by someone else!)
--
select CustColHTML_ID=0,* INTO #CustomTable2HTML FROM ' + #TABLENAME + '
IF #DEBUG=1 PRINT ''CustomTable2HTMLv2: Modfied temporary table''
--Now alter the table to add the auto-incrementing index. This will facilitate row finding
DECLARE #COUNTER INT
SET #COUNTER=0
UPDATE #CustomTable2HTML SET #COUNTER = CustColHTML_ID=#COUNTER+1
-- #HTMLROWS will store all the rows in HTML format
-- #ROW will store each HTML row as fields on each row are iterated through
-- using dymamic SQL and a cursor
DECLARE #HTMLROWS NVARCHAR(MAX)
DECLARE #ROW NVARCHAR(MAX)
SET #HTMLROWS=''''
-- #ColumnName stores the column name as found by the table cursor
-- #maxrows is a count of the rows in the table
DECLARE #ColumnName NVARCHAR(500)
DECLARE #maxrows INT
--Find row count of our temporary table
--This is used here purely to see if we have any data to output
SELECT #maxrows=count(*) FROM #CustomTable2HTML
--Create a cursor which will iterate through all the column names in the temporary table
--(excepting the one we added above)
DECLARE col CURSOR FOR
SELECT name FROM tempdb.sys.Columns
WHERE object_id=object_id(''tempdb..#CustomTable2HTML'')
AND name not like ''CustColHTML_ID''
ORDER BY column_id ASC
--For each **HTML** row, we need to for each iterate through each table column as the outer loop.
--Once the column name is identified, we use Coalesc to combine all the column values into a single string.
SET #ParmDefinition=N''#COLOUT NVARCHAR(MAX) OUTPUT''
OPEN col
FETCH NEXT FROM col INTO #ColumnName
WHILE ##FETCH_STATUS=0
BEGIN
--Using current column name, grab all column values and combine into an HTML cell string using COALESCE
SET #ROW=''''
SET #exec_str='' SELECT #COLOUT=COALESCE(#COLOUT + ''''</td>'''','''''''') + ''''<td>'''' + Cast(IsNull(['' + #ColumnName + ''],'''''''') as nvarchar(max)) from #CustomTable2HTML ''
IF #DEBUG=1 PRINT ''#exec_str: '' + #exec_str
EXEC sp_executesql
#exec_str,
#ParmDefinition,
#COLOUT=#ROW OUTPUT
SET #HTMLROWS =#HTMLROWS + ''<tr>'' + ''<td>'' + #ColumnName + ''</td>'' + #ROW + ''</tr>''
IF #DEBUG=1 SELECT #ROW as ''Current Row''
IF #DEBUG=1 SELECT #HTMLROWS as ''HTML so far..''
FETCH NEXT FROM col INTO #ColumnName
END
CLOSE col
SET #OUTPUT=''''
IF #maxrows>0
SET #OUTPUT= ''<table ' + #TBL_STYLE + '>'' + #HTMLROWS + ''</table>''
DEALLOCATE col
'
END
DECLARE #ParamDefinition nvarchar(max)
SET #ParamDefinition=N'#OUTPUT NVARCHAR(MAX) OUTPUT'
--Execute Dynamic SQL. HTML table is stored in #OUTPUT which is passed back up (as it's
--a parameter to this SP)
EXEC sp_executesql #exec_str,
#ParamDefinition,
#OUTPUT=#OUTPUT OUTPUT
RETURN 1
So, the following is mentioned in the link you have provided:
"In order to help you style your tables, in the zip download I've also
included an HTML file which has an embedded style sheet in the head
element."
So, if you open the html file they mention there, you will see they have declared the style inside the html itself.
You can only create the table via SQL and if you like, attach the class name passing it as a parameter, BUT you will need to generate a full HTML file containing the CSS (or having it referenced, it doesn't matter) in order to have your table styled.
As I mentioned in the comment, if the table will be printed horizontally or vertically is only defined by the #alignment attribute, not by the CSS class. (You can see this in the stored procedure code)

SQL Server 2008 t-SQL - Insert multiple record IDs into varchar column as CSV [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Concatenate many rows into a single text string?
I have 2 tables in SQL Server 2008 database - tblQuestion and tblSummary. I'm selecting QuestionIDs from tblQuestion as follows.
SELECT QuestionId from tblQuestion WHERE Status='Completed';
The result is as follows (from multiple records),
QuestionId
----------
1
2
5
7
8
9
[6 rows]
Now, I need to insert above selected IDs to "CompletedSections" column (which is VARCHAR type) in tblSummary. It should be inserted as a CSV like format - 1,2,5,7,8,9
For example, if I select those from tblSummary will be as follows.
SELECT CompletedSections FROM tblSummary WHERE <Some Condition>
Result should be,
CompletedSections
-----------------
1,2,5,7,8,9
[1 row]
How this can be done at the database level using t-SQL (not using any programming language like C#)? I'm hoping to implement this with t-SQL using a scheduled SQL SP/ Function/ Trigger.
Thanks,
Chatur
Here is a solution I have used in the past. It is a little hacky, but it should be faster than using a cursor to create the CSV. Here is some example code to get you started.
DECLARE #tblQuestion TABLE
(
QuestionId nvarchar(10)
)
DECLARE #tblSummary TABLE
(
CompletedSections nvarchar(100)
)
INSERT INTO #tblQuestion
VALUES (1),(2),(3),(4),(5),(6),(7),(8),(9)
INSERT INTO #tblSummary
SELECT SUBSTRING(
(SELECT ',' + QuestionId
from #tblQuestion
FOR XML PATH('')),2,200000) AS CSV
SELECT * FROM #tblSummary
This will do the job;
DECLARE #S VARCHAR(5000)
SELECT #S=ISNULL(#S+ ',', '') + CONVERT(VARCHAR(10),QuestionId)
FROM tblQuestion
SELECT #S
DECLARE #STRING VARCHAR(MAX) = ''
DECLARE #VALUE VARCHAR(MAX)
DECLARE A_CURSOR CURSOR FOR
SELECT QuestionId from tblQuestion WHERE Status='Completed'
OPEN A_CURSOR
FETCH A_CURSOR INTO #VALUE
WHILE ##FETCH_STATUS = 0
BEGIN
if #STRING <> ''
set #STRING = #STRING + ', '
set #STRING = #STRING + CONVERT(VARCHAR(MAX),#VALUE)
FETCH A_CURSOR INTO #VALUE
END
CLOSE A_CURSOR
DEALLOCATE A_CURSOR
INSERT INTO CompletedSection (tblSummary) SELECT #STRING

Dynamic sql insert into returns 'invalid column name'

I'm trying my first dynamic sql stored procedure. I need to append the exact same records into multiple tables with the same column names. What I have compiles, but when it runs I get 'invalid column name 'TradeDate. The driver sproc is first below, then the sproc containing the dynamic statement. If anyone could help, that'd be great..
ALTER PROCEDURE dbo.StoredProcedure2
AS
DECLARE #tableName varchar(120)
SET #tableName = 'tblDailyATR'
EXEC sprocAddDatesAndSymbolsToAggregatedStudy #tableName
RETURN
ALTER PROCEDURE dbo.sprocAddDatesAndSymbolsToAggregatedStudy
#table varchar(120)
AS
DECLARE #tableName varchar(120)
SET #tableName = #table
EXEC(
'INSERT INTO ' + #tableName + '(Symbol, TradeDate)
SELECT Symbol, TradingDate
FROM (SELECT tblSymbolsMain.Symbol, tblTradingDays.TradingDate
FROM tblSymbolsMain CROSS JOIN tblTradingDays
WHERE (tblTradingDays.TradingDate <= dbo.NextAvailableDataDownloadDate())) AS T1
WHERE (NOT EXISTS (SELECT TradeDate, Symbol
FROM' + #tableName +
' WHERE (TradeDate = T1.TradingDate) AND (Symbol = T1.Symbol)))')
RETURN
You're missing a space after the "FROM" in this line:
FROM' + #tableName +
Should be
FROM ' + #tableName +
Otherwise it's going to try running SELECT FROMTABLE.

Dynamic insert into variable table statement SQL Server

I have a variable table:
DECLARE #A_Table TABLE(ID INT, att1 VARCHAR(100), att2 nvarchar(200))
I want to make dynamic sql, so I insert into this table some data (all inside a loop):
WHILE (#i <= 100) BEGIN
SELECT #other_att = NAME FROM #other_Table where ID = #i;
SET #sql = 'INSERT ' + #A_Table+ '(ID,att1,att2) SELECT '+CAST(#i AS VARCHAR)+' , '''+ #other_att+''', SUM('+ #other_att') FROM '+ #EVEN_OTHER_Table;
EXEC (#sql);
END
sql every time would look like:
INSERT INTO #A_Table SELECT 1 , 'subject', SUM(subject)
INSERT INTO #A_Table SELECT 2 , 'age', SUM(age)
INSERT INTO #A_Table SELECT 3 , 'sex', SUM(sex)....
AND after executing this :
SO I will get:
#A_Table:
id att1 att2
1 subject 4.3
2 age 4.5
3 sex 4.1
but I get an error:
Msg 137, Level 16, State 1, Line 48
Must declare the scalar variable "#A_Table".
SO what is it the syntax to insert dynamically into a variable table?
Ok I have understood it.
You could use the INSERT ... EXEC syntax to insert the data returned by the dynamic SELECT. Of course, you would then need to remove the INSERT part from the dynamic statement.
WHILE (#i <= 100) BEGIN
SELECT #other_att = NAME FROM #other_Table where ID = #i;
SET #sql = 'SELECT '+CAST(#i AS VARCHAR)+' , ''' + #other_att+''', SUM('+ #other_att + ') FROM '+ #EVEN_OTHER_Table;
INSERT INTO #A_Table (ID,att1,att2)
EXEC (#sql);
END
You have a table variable, not a variable that contains the table name.
So you would need the following.
WHILE (#i <= 100) BEGIN
SELECT #other_att = NAME FROM #other_Table where ID = #i;
SET #sql = 'INSERT INTO #A_Table (ID,att1,att2) SELECT '+CAST(#i AS VARCHAR)+' , '''+ #other_att+''', SUM('+ #other_att') FROM #EVEN_OTHER_Table';
EXEC (#sql);
END
You would also need to declare the table variable as a statement inside the #sql variable, and execute your declare table and inserts together, or use a local/global temporary table.
With a local temporary table (stored in the tempdb) you could do something like this.
CREATE TABLE #testtbl (ID INT);
EXEC ('INSERT INTO #testtbl VALUES (1)');
SELECT * FROM #testtbl
DROP TABLE #testtbl
Some good info about temporary tables in BOL
http://msdn.microsoft.com/en-us/library/ms174979.aspx - quite far down the page
And the table type.
http://msdn.microsoft.com/en-us/library/ms175010.aspx
Your EXEC statement occurs in a different context and is therefore unaware of any variables created in your original context.
To create dynamic insert query it is really a task, I also struggle to find it ,finally I have tried in the following way and it's successfully working. Please find the code below.
CREATE PROCEDURE [dbo].[InsertTodaysData] (#tbl varchar(50),#Days int,
#MDate varchar(50), #EValue varchar(50), #Speed varchar(50),
#Totalreturn varchar(50),#Closingv varchar(50), #TotalReturnV varchar(50))
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
DECLARE #SQLQuery varchar(2000)
-- Insert statements for procedure here
set #SQLQuery = 'INSERT INTO '+#tbl+' (ID,MDate,EValue,Speed,TotalReturnRatio,ClosingValue,
TotalReturnValue) VALUES ('+#Days+','''+#MDate+''', '+#EValue+', '+#Speed+',
'+#Totalreturn+', '+#Closingv+', '+#TotalReturnV+')'
EXECUTE(#SQLQuery)
END
Hope this will help you..